class component
Converting a Function to a Class
You can convert a function component like Clock
to a class in five steps:
Create an ES6 class, with the same name, that extends
React.Component
.Add a single empty method to it called
render()
.Move the body of the function into the
render()
method.Replace
props
withthis.props
in therender()
body.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?