Jason Tree Jason Tree - 2 months ago 9
Javascript Question

React updateState function

I have simple update data function which currently not working:

class App extends React.Component {

constructor(props) {
super(props);

this.state = {
data: 'Initial data...'
}

this.updateState = this.updateState.bind(this);

};

updateState() {
this.setState({data: 'Data updated...'})
}

render() {
return (
<div>
<button onClick = {this.updateState}>CLICK</button>
<h4>{this.data}</h4>
</div>
);
}
}

ReactDOM.render(<App/>, document.getElementById('app'));


Below I have link to jsbin:

http://jsbin.com/vidumiroki/edit?html,js,output

Answer

You missed state in you return render function

class App extends React.Component {

   constructor(props) {
      super(props);

      this.state = {
         data: 'Initial data...'
      }

      this.updateState = this.updateState.bind(this);

   };

   updateState() {
      this.setState({data: 'Data updated...'})
   }

   render() {
      return (
         <div>
            <button onClick = {this.updateState}>CLICK</button>
            <h4>{this.state.data}</h4>
         </div>
      );
   }
}

ReactDOM.render(<App/>, document.getElementById('app'));