Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert React class components into functional components and vice versa - IntelliJ

Sometimes you want to quickly go from a statless component to a stateful component, and I'm thinking if there is some way to make IntelliJ do this for me (without creating a plugin).

For example, going from:

const Stateless = ({ propsDestructuring }) => {
  console.log('Some logic');

  return (
    <div>Some JSX</div>
  );
};

to:

class Stateful extends Component {
  render() {
    const {
      propsDestructuring
    } = this.props;

    console.log('Some logic');

    return (
      <div>Some JSX</div>
    );
  }
}

Alternatively going from "Arrow body style" to explicit return would also be useful, e.g. going from

const Stateless = ({ propsDestructuring }) => (
  <div>Some JSX</div>
);

to:

const Stateless = ({ propsDestructuring }) => {
  return (
    <div>Some JSX</div>
  );
};

Using live templates would not work in this scenario, as they can't mutate existing code, only insert new. Any suggestions?

like image 592
karl Avatar asked Sep 30 '16 08:09

karl


2 Answers

IntelliJ 2018.2 now supports this.

New intention to Convert React class components into functional components.

Instructions:

Press on the component definition:

  • Mac: options + Enter

  • Windows: Alt + Enter

It works both ways:

stateless to class component

class to stateless component

Referrence: Development with React

like image 118
karl Avatar answered Nov 15 '22 04:11

karl


You can go from:

const Stateless = ({ propsDestructuring }) => (
  <div>Some JSX</div>
);

to:

const Stateless = ({ propsDestructuring }) => {
  return (
    <div>Some JSX</div>
  );
};

By putting your text cursor here:

const Stateless = ({ propsDestructuring }) => (
-----------------------------------------^-----

And pressing alt-enter to get the following popup:

intellij popup

Press enter again to select the top result and it'll be converted to an arrow function with braces.

With regards to the function to class conversion, as far as I'm aware there's no way to do that, but you could always try using find and replace to convert:

const (.*) = \(.*\) => \{

to:

class $1 extends React.Component {

If you record this to a macro it should speed that operation up a little.

like image 36
Leon Aves Avatar answered Nov 15 '22 04:11

Leon Aves