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?
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:
Referrence: Development with React
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With