Skip to content

Latest commit

 

History

History
144 lines (100 loc) · 2.43 KB

README.md

File metadata and controls

144 lines (100 loc) · 2.43 KB

Code Mod for Class Components to Functional Components in React

Before Running

Install jscodeshift through npm

npm install -g jscodeshift

Running Script

Paste the Class Components in the sampleSource.jsx.

Run

npm run exec

What It can do

Its just kind of co-pilot not an actual transpiler.

Overview

Classic state initializtion to hook based
this.state = {
  some: "useless",
};

into

const [some, setSome] = useState("useful");

Transforming setState to appropriate hook's setState

this.setState({ some: "state", another: "state" });

into

setSome("state");
setAnother("state");

Transforming createRef to useRef hook

class Process extends Component {

    constructor() {
        this.formRef = React.createRef()
    }

    ...
}

into

const Process = () => {
    const formRef = useRef()

    ...
}

Transforming Class Member Function into Arrow Function

class Process extends Component {
    blowUp(someArg, anotherArg) {
        ...
    }

}

into

const Process = () => {
    const blowUp = (someArg, anotherArg) => {
        ...
    }
}

Moving constructor, componentDidmount to useEffect and componentWillunmount to useEffect return

class Process extends Component {

    constructor() {
        doSomething()
        ...
    }

    componentDidmount() {
        doSomethingElse()
        ...
    }

    componentWillunmount() {
        unsubscribe()
    }
}

into

const Process = () => {
  useEffect(() => {
    doSomething();
    doSomethingElse();

    return () => {
      unsubscribe();
    };
  });
};
There might some unexpected behavior which may feel buggy, yes it is. Sorry for that 😅