DEV Community

shadowtime2000
shadowtime2000

Posted on • Edited on

3

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs