• Stars
    star
    4,053
  • Rank 10,265 (Top 0.3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

React codemod scripts

react-codemod Build Status

This repository contains a collection of codemod scripts for use with JSCodeshift that help update React APIs.

Usage

npx react-codemod <transform> <path> [...options]

  • transform - name of transform, see available transforms below.
  • path - files or directory to transform
  • use the --dry option for a dry-run and use --print to print the output for comparison

This will start an interactive wizard, and then run the specified transform.

Included Transforms

create-element-to-jsx

Converts calls to React.createElement into JSX elements.

npx react-codemod create-element-to-jsx <path>

error-boundaries

Renames the experimental unstable_handleError lifecycle hook to componentDidCatch.

npx react-codemod error-boundaries <path>

findDOMNode

Updates this.getDOMNode() or this.refs.foo.getDOMNode() calls inside of React.createClass components to React.findDOMNode(foo). Note that it will only look at code inside of React.createClass calls and only update calls on the component instance or its refs. You can use this script to update most calls to getDOMNode and then manually go through the remaining calls.

npx react-codemod findDOMNode <path>

manual-bind-to-arrow

Converts manual function bindings in a class (e.g., this.f = this.f.bind(this)) to arrow property initializer functions (e.g., f = () => {}).

npx react-codemod manual-bind-to-arrow <path>

pure-component

Converts ES6 classes that only have a render method, only have safe properties (statics and props), and do not have refs to Functional Components.

The wizard will ask for 2 options -

  • Use arrow functions?: converts to arrow function. Converts to function by default.
  • Destructure props?: will destructure props in the argument where it is safe to do so.
npx react-codemod pure-component <path>

pure-render-mixin

Removes PureRenderMixin and inlines shouldComponentUpdate so that the ES2015 class transform can pick up the React component and turn it into an ES2015 class. NOTE: This currently only works if you are using the master version (>0.13.1) of React as it is using React.addons.shallowCompare

npx react-codemod pure-render-mixin <path>
  • The wizard will ask to optionally override mixin-name, and look for it instead of PureRenderMixin. Note that it is not possible to use a namespaced name for the mixin. mixins: [React.addons.PureRenderMixin] will not currently work.

React-PropTypes-to-prop-types

Replaces React.PropTypes references with prop-types and adds the appropriate import or require statement. This codemod is intended for React 15.5+.

npx react-codemod React-PropTypes-to-prop-types <path>
  • In addition to running the above codemod you will also need to install the prop-types NPM package.

rename-unsafe-lifecycles

Adds UNSAFE_ prefix for deprecated lifecycle hooks. (For more information about this codemod, see React RFC #6)

npx react-codemod rename-unsafe-lifecycles <path>

react-to-react-dom

Updates code for the split of the react and react-dom packages (e.g., React.render to ReactDOM.render). It looks for require('react') and replaces the appropriate property accesses using require('react-dom'). It does not support ES6 modules or other non-CommonJS systems. We recommend performing the findDOMNode conversion first.

npx react-codemod react-to-react-dom <path>
  • After running the automated codemod, you may want to run a regex-based find-and-replace to remove extra whitespace between the added requires, such as codemod.py -m -d src --extensions js '(var React\s*=\s*require\(.react.\);)\n\n(\s*var ReactDOM)' '\1\n\2' using https://github.com/facebook/codemod.

React-DOM-to-react-dom-factories

Converts calls like React.DOM.div(...) to React.createElement('div', ...).

npx react-codemod React-DOM-to-react-dom-factories <path>

ReactNative-View-propTypes

Replaces View.propTypes references with ViewPropTypes and adds the appropriate import or require statement. This codemod is intended for ReactNative 44+.

npx react-codemod ReactNative-View-propTypes <path>

sort-comp

Reorders React component methods to match the ESLint react/sort-comp rule. (Defaults to ordering of the Airbnb style guide.

npx react-codemod sort-comp <path>

update-react-imports

As of Babel 7.9.0, when using runtime: automatic in @babel/preset-react or @babel/plugin-transform-react-jsx, you will not need to explicitly import React for compiling jsx. This codemod removes the redundant import statements. It also converts default imports (import React from 'react') to named imports (e.g. import { useState } from 'react').

The wizard will ask for 1 option -

  • Destructure namespace imports as well?: If chosen, namespace imports like import * as React will also be converted. By default, it's false, so only default imports (import React) are converted.
npx react-codemod update-react-imports <path>

Explanation of the new ES2015 class transform with property initializers

  1. Determine if mixins are convertible. We only transform a createClass call to an ES6 class component when:
  • There are no mixins on the class, or
  • options['pure-component'] is true, the mixins property is an array and it only contains pure render mixin (the specific module name can be specified using options['mixin-module-name'], which defaults to react-addons-pure-render-mixin)
  1. Ignore components that:
  • Call deprecated APIs. This is very defensive, if the script finds any identifiers called isMounted, getDOMNode, replaceProps, replaceState or setProps it will skip the component
  • Explicitly call this.getInitialState() and/or this.getDefaultProps() since an ES6 class component will no longer have these methods
  • Use arguments in methods since arrow functions don't have arguments. Also please notice that arguments should be very carefully used and it's generally better to switch to spread (...args) instead
  • Have inconvertible getInitialState(). Specifically if you have variable declarations like var props = ... and the right hand side is not this.props then we can't inline the state initialization in the constructor due to variable shadowing issues
  • Have non-primitive right hand side values (like foo: getStuff()) in the class spec
  1. Transform it to an ES6 class component
  2. Replace var A = React.createClass(spec) with class A extends React.Component {spec}. If a component uses pure render mixin and passes the mixins test (as described above), it will extend React.PureComponent instead - Remove the require/import statement that imports pure render mixin when it's no longer being referenced
  3. Pull out all statics defined on statics plus the few special cased statics like childContextTypes, contextTypes, displayName, getDefaultProps(), and propTypes and transform them to static properties (static propTypes = {...};) - If getDefaultProps() is simple (i.e. it only contains a return statement that returns something) it will be converted to a simple assignment (static defaultProps = ...;). Otherwise an IIFE (immediately-invoked function expression) will be created (static defaultProps = function() { ... }();). Note that this means that the function will be executed only a single time per app-lifetime. In practice this hasn't caused any issues — getDefaultProps should not contain any side-effects
  4. Transform getInitialState() - If there's no getInitialState() or the getInitialState() function is simple (i.e., it only contains a return statement that returns something) then we don't need a constructor; state will be lifted to a property initializer (state = ...;)
    • However, if the RHS of return contains references to this other than this.props and/or this.context, we can't be sure about what you'll need from this. We need to ensure that our property initializers' evaluation order is safe, so we defer state's initialization by moving it all the way down until all other property initializers have been initialized - If getInitialState() is not simple, we create a constructor and convert getInitialState() to an assignment to this.state
    • constructor always have props as the first parameter
    • We only put context as the second parameter when (one of) the following things happen in getInitialState():
      • It accesses this.context, or
      • There's a direct method call this.x(), or
      • this is referenced alone
    • Rewrite accesses to this.props to props and accesses to this.context to context since the values will be passed as constructor arguments
      • Remove simple variable declarations like var props = this.props; and var context = this.context
    • Rewrite top-level return statements (return {...};) to this.state = {...}
      • Add return; after the assignment when the return statement is part of a control flow statement (not a direct child of getInitialState()'s body) and not in an inner function declaration
  5. Transform all non-lifecycle methods and fields to class property initializers (like onClick = () => {};). All your Flow annotations will be preserved - It's actually not necessary to transform all methods to arrow functions (i.e., to bind them), but this behavior is the same as createClass() and we can make sure that we won't accidentally break stuff
  6. Generate Flow annotations from propTypes and put it on the class (this only happens when there's /* @flow */ in your code and options['flow'] is true)
  • Flow actually understands propTypes in createClass calls but not ES6 class components. Here the transformation logic is identical to how Flow treats propTypes
  • Notice that Flow treats an optional propType as non-nullable
    • For example, foo: React.PropTypes.number is valid when you pass {}, {foo: null}, or {foo: undefined} as props at runtime. However, when Flow infers type from a createClass call, only {} and {foo: undefined} are valid; {foo: null} is not. Thus the equivalent type annotation in Flow is actually {foo?: number}. The question mark on the left hand side indicates {} and {foo: undefined} are fine, but when foo is present it must be a number
  • For propTypes fields that can't be recognized by Flow, $FlowFixMe will be used
  1. React.createClass is no longer present in React 16. So, if a createClass call cannot be converted to a plain class, the script will fallback to using the create-react-class package.
  • Replaces React.createClass with ReactCreateClass.
  • Adds a require or import statement for create-react-class. The import style is inferred from the import style of the react import. The default module name can be overridden with the --create-class-module-name option.
  • Prunes the react import if there are no more references to it.

Usage

npx react-codemod class <path>

jscodeshift options

To pass more options directly to jscodeshift, use --jscodeshift="...". For example:

npx react-codemod --jscodeshift="--run-in-band --verbose=2"

See all available options here.

Recast Options

Options to recast's printer can be provided through jscodeshift's printOptions command line argument

npx react-codemod <transform> <path> --jscodeshift="--printOptions='{\"quote\":\"double\"}'"

explicit-require=false

If you're not explicitly importing React in your files (eg: if you're loading React with a script tag), you should add --explicit-require=false.

Support and Contributing

The scripts in this repository are provided in the hope that they are useful, but they are not officially maintained, and we generally will not fix community-reported issues. They are a collection of scripts that were previously used internally within Facebook or were contributed by the community, and we rely on community contributions to fix any issues discovered or make any improvements. If you want to contribute, you're welcome to submit a pull request.

License

react-codemod is MIT licensed.

More Repositories

1

react.dev

The React documentation website
TypeScript
10,714
star
2

react-transition-group

An easy way to perform animations when a React component enters or leaves the DOM
JavaScript
10,074
star
3

react-router-redux

Ruthlessly simple bindings to keep react-router and redux in sync
JavaScript
7,824
star
4

react-modal

Accessible modal dialog component for React
JavaScript
7,314
star
5

react-rails

Integrate React.js with Rails views and controllers, the asset pipeline, or webpacker.
JavaScript
6,725
star
6

react-router-tutorial

JavaScript
5,532
star
7

rfcs

RFCs for changes to React
5,377
star
8

react-basic

A description of the conceptual model of React without implementation burden.
4,163
star
9

server-components-demo

Demo app of React Server Components.
JavaScript
4,140
star
10

react-docgen

A CLI and library to extract information from React component files for documentation generation purposes.
TypeScript
3,557
star
11

react-tutorial

Code from the React tutorial.
JavaScript
3,294
star
12

react-tabs

An accessible and easy tab component for ReactJS.
JavaScript
3,048
star
13

react-chartjs

common react charting components using chart.js
JavaScript
2,930
star
14

react-future

Specs & docs for potential future and experimental React APIs and JavaScript syntax.
JavaScript
2,824
star
15

express-react-views

This is an Express view engine which renders React components on server. It renders static markup and *does not* support mounting those views on the client.
JavaScript
2,732
star
16

react-a11y

Identifies accessibility issues in your React.js elements
JavaScript
2,332
star
17

React.NET

.NET library for JSX compilation and server-side rendering of React components
C#
2,269
star
18

react-autocomplete

WAI-ARIA compliant React autocomplete (combobox) component
JavaScript
2,161
star
19

react-art

React Bridge to the ART Drawing Library
JavaScript
1,987
star
20

react-php-v8js

PHP library that renders React components on the server
PHP
1,325
star
21

react-magic

Automatically AJAXify plain HTML with the power of React. It's magic!
JavaScript
939
star
22

core-notes

Weekly meeting notes from the React core team
899
star
23

zh-hans.react.dev

React documentation website in Simplified Chinese
TypeScript
876
star
24

ru.react.dev

React documentation website in Russian / Официальная русская версия сайта React
TypeScript
673
star
25

ko.react.dev

React documentation website in Korean
TypeScript
660
star
26

pt-br.react.dev

🇧🇷 React documentation website in Portuguese (Brazil)
TypeScript
465
star
27

react-lifecycles-compat

Backwards compatibility polyfill for React class components
JavaScript
459
star
28

react-gradual-upgrade-demo

Demonstration of how to gradually upgrade an app to a new version of React
JavaScript
420
star
29

react-timer-mixin

TimerMixin provides timer functions for executing code in the future that are safely cleaned up when the component unmounts
JavaScript
309
star
30

id.react.dev

(Work in progress) React documentation website in Indonesian
TypeScript
305
star
31

es.react.dev

React documentation website in Spanish / Documentación del sitio web de React en Español
TypeScript
272
star
32

translations.react.dev

Nexus of resources and tools for translating the React docs.
JavaScript
254
star
33

ja.react.dev

React documentation website in Japanese
TypeScript
243
star
34

react-static-container

Renders static content efficiently by allowing React to short-circuit the reconciliation process.
JavaScript
222
star
35

fa.react.dev

(Work in progress) React documentation website in Persian
TypeScript
182
star
36

tr.react.dev

React documentation website in Turkish
TypeScript
161
star
37

uk.react.dev

🇺🇦 React documentation website in Ukrainian / Офіційна українська версія сайту React
TypeScript
130
star
38

ar.react.dev

React documentation website in Arabic 📘⚛️ — وثائق React باللغة العربية
TypeScript
126
star
39

hi.react.dev

(Work in progress) React documentation website in Hindi
TypeScript
110
star
40

zh-hant.react.dev

(Work in progress) React documentation website in Traditional Chinese
TypeScript
105
star
41

bn.react.dev

(Work in progress) React documentation website in Bengali
TypeScript
98
star
42

fr.react.dev

Version française du site de documentation officiel de React
TypeScript
91
star
43

vi.react.dev

(Work in progress) React documentation website in Vietnamese
TypeScript
84
star
44

react-bower

[DISCONTINUED] Bower package for React
JavaScript
69
star
45

legacy.reactjs.org

An archived copy of the legacy React documentation website
JavaScript
60
star
46

bn.reactjs.org

(Work in progress) React documentation website in Bengali
JavaScript
54
star
47

ta.reactjs.org

(Work in progress) React documentation website in Tamil
JavaScript
52
star
48

pl.react.dev

React documentation website in Polish
TypeScript
49
star
49

az.react.dev

🇦🇿 React documentation website in Azerbaijani
TypeScript
43
star
50

rackt-codemod

Codemod scripts for Rackt libraries
JavaScript
40
star
51

th.reactjs.org

(Work in progress) React documentation website in Thai
JavaScript
40
star
52

mn.react.dev

(Work in progress) React documentation website in Mongolian
TypeScript
37
star
53

uz.reactjs.org

(Work in progress) React documentation website in Uzbek
TypeScript
36
star
54

de.react.dev

(Work in progress) React documentation website in German
TypeScript
33
star
55

si.reactjs.org

(Work in progress) React documentation website in Sinhala
JavaScript
32
star
56

ml.react.dev

(Work in progress) React documentation website in Malayalam
TypeScript
31
star
57

it.react.dev

(Work in progress) React documentation website in Italian
TypeScript
30
star
58

ur.reactjs.org

(⚠️ Beta Docs Translation only) React documentation website in Urdu. Check details in https://github.com/reactjs/ur.reactjs.org/issues/1#issuecomment-949791355
TypeScript
29
star
59

he.react.dev

(Work in progress) React documentation website in Hebrew
TypeScript
28
star
60

ku.reactjs.org

(Work in progress) React documentation website in Kurdish
JavaScript
28
star
61

hu.react.dev

Hungarian 🇭🇺 React ⚛ documentation 📚 / React magyar dokumentációja
TypeScript
26
star
62

be.react.dev

(Work in progress) React documentation website in Belarusian
TypeScript
26
star
63

ml.reactjs.org

(Work in progress) React documentation website in Malayalam
JavaScript
25
star
64

ur.react.dev

(Work in progress) React documentation website in Urdu
TypeScript
25
star
65

el.reactjs.org

(Work in progress) React documentation website in Greek
JavaScript
25
star
66

gu.react.dev

(Work in progress) React documentation website in Gujarati
TypeScript
24
star
67

pt-PT.reactjs.org

(Work in progress) React documentation website in Portuguese (Portugal) 🇵🇹
JavaScript
23
star
68

ne.reactjs.org

(Work in progress) React documentation website in Nepali
JavaScript
23
star
69

gu.reactjs.org

(Work in progress) React documentation website in Gujarati
JavaScript
22
star
70

te.reactjs.org

(Work in progress) React documentation website in Telugu
JavaScript
22
star
71

hy.reactjs.org

(Work in progress) React documentation website in Armenian - https://hy.reactjs.org
JavaScript
21
star
72

km.reactjs.org

(Work in progress) React documentation website in Central Khmer
JavaScript
20
star
73

bg.reactjs.org

(Work in progress) React documentation website in Bulgarian
JavaScript
16
star
74

ro.reactjs.org

(Work in progress) React documentation website in Romanian
JavaScript
16
star
75

si.react.dev

(Work in progress) React documentation website in Sinhala
TypeScript
14
star
76

kn.reactjs.org

(Work in progress) React documentation website in Kannada
JavaScript
13
star
77

tl.reactjs.org

(Work in progress) React documentation website in Tagalog
TypeScript
13
star
78

ka.reactjs.org

(Work in progress) React documentation website in Georgian
JavaScript
11
star
79

sv.reactjs.org

(Work in progress) React documentation website in Swedish
JavaScript
9
star
80

nl.reactjs.org

(Work in progress) React documentation website in Dutch
JavaScript
8
star
81

ca.reactjs.org

(Work in progress) React documentation website in Catalan
JavaScript
7
star
82

te.react.dev

(Work in progress) React documentation website in Telugu
TypeScript
7
star
83

sw.react.dev

(Work in progress) React documentation website in Swahili
TypeScript
7
star
84

lt.reactjs.org

(Work in progress) React documentation website in Lithuanian
JavaScript
6
star
85

ta.react.dev

(Work in progress) React documentation website in Tamil
TypeScript
6
star
86

ht.reactjs.org

(Work in progress) React documentation website in Haitian Creole
JavaScript
5
star
87

sr.reactjs.org

(Work in progress) React documentation website in Serbian
TypeScript
5
star
88

is.react.dev

(Work in progress) React documentation website in Icelandic
TypeScript
4
star
89

cs.react.dev

(Work in progress) React documentation website in Czech
TypeScript
4
star
90

kk.react.dev

🇰🇿 React documentation website in Kazakh / React сайтының ресми қазақша нұсқасы
TypeScript
3
star
91

sr.react.dev

(Work in progress) React documentation website in Serbian
TypeScript
3
star
92

sq.reactjs.org

(Work in progress) React documentation website in Albanian
TypeScript
3
star
93

reactjs.github.io

HTML
2
star
94

lo.react.dev

(Work in progress) React documentation website in Lao
TypeScript
2
star
95

fi.react.dev

(Work in progress) React documentation website in Finnish
TypeScript
2
star
96

my.reactjs.org

(Work in progress) React documentation website in Burmese
JavaScript
2
star
97

sw.reactjs.org

(Work in progress) React documentation website in Swahili
JavaScript
2
star
98

mk.react.dev

(Work in progress) React documentation website in Macedonian
TypeScript
1
star
99

tg.reactjs.org

(Work in progress) React documentation website in Tajik
TypeScript
1
star