Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot change the state of a react component using setState() method

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 –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading