Home

Awesome

babel-plugin-transform-react-class-to-function

A Babel 7 plugin which transforms React component classes into functions

npm version build status codecov

Writing React components using the class syntax has several benefits:

There is one obvious downside:

This plugin solves that for you. πŸ˜ƒ

Example

In

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>;
  }
}

Out

import PropTypes from 'prop-types';
import { Component } from 'react';

export const HelloWorld = ({ className }) => <div className={className}>Hello world!</div>;

HelloWorld.propTypes = {
  className: PropTypes.string,
};

Installation

npm install @babel/core babel-plugin-transform-react-class-to-function

Usage

Via babel.config.js (Recommended)

module.exports = (api) => ({
  plugins: ['babel-plugin-transform-react-class-to-function'],
});

Via CLI

babel --plugins babel-plugin-transform-react-class-to-function

Via Node API

require('@babel/core').transform(code, {
  plugins: ['babel-plugin-transform-react-class-to-function'],
});

Options

memo

Special Thanks

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.