I am a beginner and I am trying to see how stateful components work in react. I have implemented a simple functionality where I would click a button and change the state of the content that I am rendering on the DOM.
But, after using the setState
method in the event handler, the output doesn’t give the desired results.
Here is the code –
class MyComponent extends React.Component{
constructor(props)
{
super(props);
this.state ={
content: "Initial Content"
};
}
clickHandler()
{
this.setState({
content: "Final Content"
})
console.log("Clicked")
}
render()
{
return (
<div>
<h1>The content inside the state is: {this.state.content}</h1>
<button onClick={this.clickHandler} >Click Me</button>
</div>
);
}
}
Please correct me if there are some issues in the code
>Solution :
The code is almost correct. You just need to bind the event handler, to ensure that this
refers to the component instance within the event handler.
Here is the updated version:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
content: "Initial Content"
};
// Binding the event handler to the component instance
this.clickHandler = this.clickHandler.bind(this);
}
clickHandler() {
this.setState({
content: "Final Content"
});
console.log("Clicked");
}
render() {
return (
<div>
<h1>The content inside the state is: {this.state.content}</h1>
<button onClick={this.clickHandler}>Click Me</button>
</div>
);
}
}
ReactDOM.render(<MyComponent />,document.querySelector("#root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>