'Why is setState not working in the event handler? [duplicate]

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();


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source