class component

Converting a Function to a Class

You can convert a function component like Clock to a class in five steps:

  1. Create an ES6 class, with the same name, that extends React.Component.

  2. Add a single empty method to it called render().

  3. Move the body of the function into the render() method.

  4. Replace props with this.props in the render() body.

  5. Delete the remaining empty function declaration.

Constructor

  constructor(props) {
    super(props);    
    this.state = {date: new Date()};
  }

In JavaScript, super refers to the parent class constructor. (In our example, it points to the React.Component implementation.)

Importantly, you can’t use this in a constructor until after you’ve called the parent constructor. JavaScript won’t let you:

Last updated

Was this helpful?