ECMAScript2015(ES6) is the latest version of the ECMAScript standard.
React is a declarative, efficient, and flexible JavaScript library for building user interfaces.
In the earlier days of React development, many programms were written in ES5. Howerver, as ES6 is more widely accepted now and with the help of transplier tools like Babel, we can gradually retire some ES5 code and adopt some ES6 new features in React development.
Here is a check list to help you translate your ES5 code to newer version in React. You are welcome to contribute with more items provided below.
Quick links
- require => import
- createClass => extends React.Component
- module.exports => export default
- name: function() => name()
- getDefaultProps and propTypes
- getInitialState
- Destructuring & spread attributes
require-to-import
ES5
//ES5var React = ; var PropTypes = ReactPropTypes;
ES6
;
createClass-to-extends
ES5
var Mycomponent = React;
ES6
Component { return <div>ES6</div> ; }
module-exports-to-export-default
ES5
var Mycomponent = React; moduleexports = Mycomponent;
ES6
Component { return <div>ES6</div> ; }
functions
ES5
var Mycomponent = React; moduleexports = Mycomponent;
ES6
Component { } { return <div>ES6</div> ; }
getDefaultProps-and-propTypes
ES5
var Video = React;
ES6
Component { return <View /> ; }VideodefaultProps = autoPlay: false maxLoops: 10;VideopropTypes = autoPlay: ReactPropTypesboolisRequired maxLoops: ReactPropTypesnumberisRequired posterFrameSrc: ReactPropTypesstringisRequired videoSrc: ReactPropTypesstringisRequired;
ES7:
Component static defaultProps = autoPlay: false maxLoops: 10 static propTypes = autoPlay: ReactPropTypesboolisRequired maxLoops: ReactPropTypesnumberisRequired posterFrameSrc: ReactPropTypesstringisRequired videoSrc: ReactPropTypesstringisRequired state = loopsRemaining: thispropsmaxLoops
getInitialState
ES5
var Header = React;
ES6
{ superprops; thisstate = title: propstitle ; }
ES7
state = title: thispropstitle ; // followed by constructor...
Destructuring-and-spread-attributes
Component { var className ...others // contains all properties of this.props except for className = thisprops; return <div className=className> <PostsGrid ...others /> <button onClick=thishandleLoadMoreClick>Load more</button> </div> ; }
Reference
- React
- Babel
- ECMAScript 6 support in Mozilla
- React on ES6+
- Converting React project from ES5 to ES6
- React/React Native 的ES5 ES6写法对照表
Roadmap
- Include all ES5 to ES6+ instructions for React
- We may Implement ESlint plugin like ESlint-Plugin-React-5-to-6
- We may Include instructions for configuring Babel with different stages
License
MIT