user944513 user944513 - 6 months ago 18
Javascript Question

how to set value on button click in react js?

I want to change the state value on button click using react js.I am able to get click event .But the set value not updated why .I used this

btnClick(){
alert('---')
// this.setState({data: 'nannsd'});
this.state ={data: 'sds'};
}


here is my code
http://codepen.io/naveennsit/pen/MydPJM

class App extends React.Component{
constructor(){
super();
this.state ={data: 'test'};
}
btnClick(){
alert('---')
// this.setState({data: 'nannsd'});
this.state ={data: 'sds'};
}

render(){
return <div>
hello {this.state.data}
<button onClick={this.btnClick}>click</button>
</div>
}

}

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

Answer

Two things:

1) Outside the constructor, you should call setState (instead of directly setting state). It looks like you probably tried this since it's commented out.

2) You need to bind this, so that you have the right value inside btnClick.

Here's a quick fork of your codepen with this fixed up. http://codepen.io/juliepagano/pen/xVNyrO

class App extends React.Component{
  constructor(){
    super();
    this.state ={data: 'test'};
  }

  btnClick(){
    alert('---')
   this.setState({data: 'nannsd'});
     // this.state ={data: 'sds'};
  }

  render(){
    return <div>
      hello {this.state.data}
      <button onClick={this.btnClick.bind(this)}>click</button>
    </div>
  }

}

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