How can you update the state of a component?
Answer / Meenakshi Kumari
To update the state of a component in React, use the `setState()` method provided by React. The general approach is to define a new state object with the desired changes and pass it as an argument to `setState()`. Here's an example:
```
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<button onClick={this.handleClick}>Click me</button>
<p>The count is {this.state.count}</p>
</div>
);
}
}
```
| Is This Answer Correct ? | 0 Yes | 0 No |
How can a browser read JSX file?
What is the difference between npm & npx?
How to build the React app for production?
Explain basic code snippet of jsx with the help of a practical example?
How to update the state of the component in reactjs?
What are components in reactjs? Explain the component lifecycle with the help of a diagram explaining each component method in detail. Also, give an example of both stateless and stateful components with source code?
Why should I use react js?
What do you understand with the term polling?
Differentiate between states and props.
What is the purpose of render() function in reactjs?
What are the lifecycle methods of reactjs components?
What is props?