Skip to content

fix(codemod): improve replace-string-ref accuracy - #1310

Closed
henryqdineen wants to merge 1 commit into
codemod:mainfrom
henryqdineen:hqd-replace-string-ref-robust
Closed

fix(codemod): improve replace-string-ref accuracy#1310
henryqdineen wants to merge 1 commit into
codemod:mainfrom
henryqdineen:hqd-replace-string-ref-robust

Conversation

@henryqdineen

@henryqdineen henryqdineen commented Sep 4, 2024

Copy link
Copy Markdown
Contributor

📚 Description

We ran the replace-string-ref codemod at scale and noticed a couple issues that could cause bugs.

<div
  ref={(ref) => {
    this.refs.refName = ref;
  }}
/>;

This code above behaves differently than string refs because when the div in unmounted this.refs.refName is set to null instwead of the refName property being deleted. This can cause issues if you have logic in your code that relies on typeof this.ref.refName.

My first thought was to do this.refs.refName = ref ?? undefined but you can still run into issues if your code relies on stuff like 'refName' in this.refs, Object.keys(this.refs).length, etc.

I think some of these scenarios are unlikely so feel free to close this but I just wanted to call out this gotcha. It also might help to confirm with somebody from the React team if this is truly a more accurate replacement.

A bonus with this change is that you no longer run into the TypeScript error:

Type 'HTMLDivElement | null' is not assignable to type 'ReactInstance'.
  Type 'null' is not assignable to type 'ReactInstance'.

🧪 Test Plan

Added unit test

@vercel

vercel Bot commented Sep 4, 2024

Copy link
Copy Markdown

@henryqdineen is attempting to deploy a commit to the Codemod Team on Vercel.

A member of the Team first needs to authorize it.

@pkg-pr-new

pkg-pr-new Bot commented Sep 4, 2024

Copy link
Copy Markdown

Open in Stackblitz

pnpm add https://pkg.pr.new/codemod@1310

commit: f26f680

@alexbit-codemod

Copy link
Copy Markdown
Contributor

will push the fix here: codemod/react-codemod#6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants