How can I convert a class with a constructor to a functional component using React Hooks?

Viewed 491

How can I convert the below class with a constructor to a functional component using React Hooks?

class App extends React.Component {
  constructor(props) {
    super(props);
    this.toggleVisibility = this.toggleVisibility.bind(this);
    this.handleOnBlur = this.handleOnBlur.bind(this);
  }

I saw somewhere online that you can do something like this for the constructor:

const useConstructor(callBack = () => {}) {
  const [hasBeenCalled, setHasBeenCalled] = useState(false);
  if (hasBeenCalled) return;
  callBack();
  setHasBeenCalled(true);
}

And then change the class to a function and use it like this:

const App = () => {
  useConstructor(() => {});

But I'm not sure what to do with toggleVisibility and handleOnBlur

2 Answers

You no need to use a constructor inside the functional components ( unless some difficult specific issue ). You can do it like simple arrow functions inside functional component like that:

const App = props => {
    const toggleVisibility = toggleProps => {
        console.log('toggleProps should be true', toggleProps);
    };

    const handleOnBlur = () => {};

    return (
        <>
            <button onClick={handleOnBlur} />
            <button
                onClick={() => {
                    toggleVisibility(true);
                }}
            />
        </>
    );
};

No need for binding and useConstructor, the following should be equivalent:

const App = (props) => {
  let toggleVisibility;
  let handleOnBlur;
  // ... rest of your component logic
}
Related