@putout/plugin-react-hooks [![NPM version][NPMIMGURL]][NPMURL]

June 13, 2023 ยท View on GitHub

๐ŸŠPutout plugin adds ability to convert class components to react hooks. Not bundled.

Install

npm i putout @putout/plugin-react-hooks -D

Add .putout.json with:

{
    "plugins": ["react-hooks"]
}

Rules

Here is list of rules:

{
    "rules": {
        "react-hooks/apply-short-fragment": "on",
        "react-hooks/declare": "on",
        "react-hooks/rename-method-under-score": "on",
        "react-hooks/convert-state-to-hooks": "on",
        "react-hooks/remove-bind": "on",
        "react-hooks/remove-this": "on",
        "react-hooks/remove-react": "on",
        "react-hooks/convert-class-to-function": "on",
        "react-hooks/convert-component-to-use-state": "on",
        "react-hooks/convert-import-component-to-use-state": "on"
    }
}

apply-short-fragment

Apply shorthand syntax of Fragment. Check out in ๐ŸŠPutout Editor.

โŒ Example of incorrect code

function Columns() {
    return (
        <Fragment>
            <td>Hello</td>
            <td>World</td>
        </Fragment>
    );
}

โœ… Example of correct code

function Columns() {
    return (
        <>
            <td>Hello</td>
            <td>World</td>
        </>
    );
}

Comparison

LinterRuleFix
๐ŸŠ Putoutreact-hooks/apply-short-fragmentโœ…
โฃ ESLintreact/jsx-fragmentsโœ…

declare

Declare hooks according to Hooks API Reference.

โŒ Example of incorrect code

function Example() {
    const [count, setCount] = useState(0);
    
    return (
        <div/>
    );
}

โœ… Example of correct code

import {useState} from 'react';

function Example() {
    const [count, setCount] = useState(0);
    
    return (
        <div/>
    );
}

remove-react

Remove import of React in a similar to react-codemod way.

โŒ Example of incorrect code

import React, {useState} from 'react';

โœ… Example of correct code

import {useState} from 'react';

Example

Consider example using class:

import React, {Component} from 'react';

export default class Button extends Component {
    constructor() {
        super();
        
        this.state = {
            enabled: true,
        };
        
        this.toggle = this._toggle.bind(this);
    }
    
    _toggle() {
        this.setState({
            enabled: false,
        });
    }
    
    render() {
        const {enabled} = this.state;
        
        return (
            <button
                enabled={enabled}
                onClick={this.toggle}
            />
        );
    }
}

After putout --fix transform, you will receive:

import React, {useState} from 'react';

export default function Button() {
    const [enabled, setEnabled] = useState(true);
    
    function toggle() {
        setEnabled(false);
    }
    
    return (
        <button
            enabled={enabled}
            onClick={toggle}
        />
    );
}

License

MIT