DEV Community

shadowtime2000
shadowtime2000

Posted on • Edited on

React Class to Functional Component Babel Plugin

I was interested in how tools that analyze and change your code like Babel, ESLint, and Prettier work. I thought to myself, why not make a Babel plugin? So I did.

Overview

This Babel plugin searches for VariableDeclarations and converts them into functional components. Because of limitations and such components cannot use ES6 classes or JSX.

Demo

This:

import React from "react";

const Hey = React.createClass({
  componentDidMount() {
    console.log("a");
    console.log("b");
  },

  render() {
    return React.createElement("div", null, "Hey!");
  },
});

export default Hey;
Enter fullscreen mode Exit fullscreen mode

becomes this:

import React from "react";

function Hey(props) {
  function componentDidMount() {
    console.log("a");
    console.log("b");
  }

  useEffect(componentDidMount);
  return React.createElement(
    "div",
    null,
    "Hey!"
  );
}

export default Hey;
Enter fullscreen mode Exit fullscreen mode

Contributing

Pull requests are welcome if they add new features or integrate more hooks.

Github
NPM

Top comments (0)