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:
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
// import React from react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
animal: 'dog',
color: 'black'
};
}
render() {
return (
<div>
<p>
animal: = {this.state.animal},
color: = {this.state.color}
</p>
</div>
);
}
}
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
Note:
Go to this article to see functional component example.