First of all, let’s understand why we need to do that.
We saw earlier in this Components and Props in React post that you can declare the components in two different ways. No matter which method you use to do so, one thing is clear. It must not modify its props.
That’s where the states concept comes into play.
So, we learned How to convert a function component into a class in React?
Now, let’s modify that class and add a local state method.
This is our class without local state method.
class Clock extends React.Component {
render(){
return (
Hello, world!
It is {this.props.date.toLocaleTimeString()}.
);
}
}
Step 1: Replace this.props.date with this.state.date.
class Clock extends React.Component {
render(){
return (
Hello, world!
It is {this.state.date.toLocaleTimeString()}.
);
}
}
Step 2: Add a constructor.
We still need to pass the value for date. For that we’ll add a constructor inside the class with initial props this.state.
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
return (
Hello, world!
It is {this.state.date.toLocaleTimeString()}.
);
}
}
As you have noticed in the code above, we are passing the props to constructor now. Before, we’re passing that to a function since there was no class.
Class components should always call the base constructor with props.
Step 3: Remove props from the element.
If you’ve added the prop in the element to make the function component work, remove that now since we have a constructor to take the props.
Change this:
ReactDOM.render(
,
document.getElementById('root')
);
to this:
ReactDOM.render(
,
document.getElementById('root')
);
That’s it. We just added a local state method to a class.
class functions local state states