0

I wrote a simple React app having a class Component and a name state in it. I am expecting to change the state name value via button click But it doesn't work

Here is my code :

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

class Demo extends React.Component {
  state ={
    name:"Hello"
  }
  fun() {
    this.setState({
      name:"World"
    });
  }
  render() {
    return <p>{this.state.name+" "}<br/><button onClick={this.fun}>Click</button></p>;
  }
}
ReactDOM.render(
  <Demo/>,
  document.getElementById('root')
);
reportWebVitals();
Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
  • 2
    The `this` binding is being lost. For the reason why, please read the questions linked. To solve it for your issue use `onClick={() => this.fun()}` or bind the `this` value to the method in the constructor. – evolutionxbox Feb 15 '22 at 13:47

0 Answers0