react-codemod icon indicating copy to clipboard operation
react-codemod copied to clipboard

feat: Add codemod to transform string refs to arrow-functions

Open eps1lon opened this issue 3 years ago • 2 comments

For https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md#deprecate-string-refs-and-remove-production-mode-_owner-field

In: <div ref="refComponent" />; Out:

<div
  ref={(current) => {
    this.refs['refComponent'] = current;
  }}
/>

Note that this codemod only works for React 18.3 or higher.

Should not be used if the codebase contains warnings about string refs without owners e.g.

Component "ComponentNameWithRef" contains the string ref "someStringRefName". 
Support for string refs will be removed in a future major release.
This case cannot be automatically converted to an arrow function.
We ask you to manually fix this case by using useRef() or createRef() instead.
Learn more about using refs safely here:
https://reactjs.org/link/strict-mode-string-ref

Test plan

  • yarn test
  • node bin/react-codemod.js string-refs ~/repos/react

eps1lon avatar Sep 25 '22 12:09 eps1lon

We decided against a codemdoddable warning

eps1lon avatar Jan 02 '23 17:01 eps1lon

The plan is to land unfreezing this.refs for 18.3 and 19. Then we can use this codemod.

eps1lon avatar Apr 17 '24 22:04 eps1lon