A Babel 7 plugin which transforms React component classes into functions
Writing React components using the class syntax has several benefits:
- Consistency — Define all components using similar syntax.
- Static properties — Components are more self contained when using static class properties.
- Simpler diffs — No need to change the entire indentation converting between classes and functions.
There is one obvious downside:
- Size — Class components are larger than function components.
This plugin solves that for you. 😃
import PropTypes from 'prop-types';
import { Component } from 'react';
export class HelloWorld extends Component {
static propTypes = {
className: PropTypes.string,
};
render() {
const { className } = this.props;
return <div className={className}>Hello world!</div>;
}
}
import PropTypes from 'prop-types';
import { Component } from 'react';
export const HelloWorld = ({ className }) => <div className={className}>Hello world!</div>;
HelloWorld.propTypes = {
className: PropTypes.string,
};
npm install @babel/core babel-plugin-transform-react-class-to-function
module.exports = (api) => ({
plugins: ['babel-plugin-transform-react-class-to-function'],
});
babel --plugins babel-plugin-transform-react-class-to-function
require('@babel/core').transform(code, {
plugins: ['babel-plugin-transform-react-class-to-function'],
});
true
: TransformPureComponent
and components implementingshouldComponentUpdate
to functional components using React memo.false
(default): Don’t transformPureComponent
or components implementingshouldComponentUpdate
.
This plugin was originally based on babel-plugin-transform-react-pure-class-to-function. However, the project has diverged a lot. You may want to give that project a try if you need to use babel 6.