EN
React - use state in a component (class component)
0 points
In this article, we would like to show you how to use state in React.
Below example presents a class component with state
object where we store property values that belong to the component.
We refer to the state
object by using this.state.propertyname
(in our case this.state.animal
).
Note: When the state changes, the component re-renders.
Runnable example:
xxxxxxxxxx
1
//Note: Uncomment import lines during working with JSX Compiler.
2
// import React from react';
3
4
class App extends React.Component {
5
constructor(props) {
6
super(props);
7
this.state = {
8
animal: 'dog',
9
color: 'black'
10
};
11
}
12
render() {
13
return (
14
<div>
15
<p>
16
animal: = {this.state.animal},
17
color: = {this.state.color}
18
</p>
19
</div>
20
);
21
}
22
}
23
24
const root = document.querySelector('#root');
25
ReactDOM.render(<App />, root );
Note:
Go to this article to see functional component example.