State in React JS
State is a way to manage the data of a component. When the state of a component changes, React automatically updates the UI. Here's an example of a class component that uses state:
jsx
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.handleClick()}>Increment</button>
</div>
);
}
}
ReactDOM.render(
<Counter />,
document.getElementById('root')
);
In this example, the Counter component has a state variable count which is initialized to 0 in the constructor. When the button is clicked, the handleClick method is called which updates the state by incrementing the count.
No comments:
Post a Comment