Praveen Raj
Praveen Raj

Reputation: 1014

Why this.state is not working in render()

I am new to ReactJs.I tried a small snippet with React.But this.state is not working in ES6 ReactJs.Help me what I am missing!!

JS without ES6:

 var App = React.createClass({
      getInitialState: function() {
        return {value:''};
      },

      handleClick: function(e){
        this.setState({value:e.target.value});
        console.log(this.state.value);//getting value here
      },
      render: function() {
        return(
          <div>
            Hello {this.props.name}
            <input type="text" onChange={this.handleClick}/>
            {this.state.value}// no value
          </div>);
      }
    });
    React.render(<App name="Praveen" />, document.getElementById('content'));

This case is working fine. Jsbin code

JS with ES6:

class App extends React.Component {
  constructor(props){
    super(props)
    this.state ={value:''};
  }
  handleClick(e){
    this.setState({value:e.target.value});
    console.log(this.state.value);//getting value here
  }
  render() {
    return(
      <div>
        Hello {this.props.name}
        <input type="text" onChange={this.handleClick}/>
        {this.state.value}// no value
      </div>);
  }
}
React.render(<App name="Praveen" />, document.getElementById('content'));

In this case whenever I am setting this.setState() render function is not called. Jsbin code

Upvotes: 3

Views: 7223

Answers (2)

Yangshun Tay
Yangshun Tay

Reputation: 53169

For performance reasons, it is recommended to do the binding in the constructor instead so that the binding only happens upon initialization instead of on every render.

Read more about event handlers on React docs here.

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {value:''};
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e) {
    this.setState({value:e.target.value}, () => {
      console.log(this.state.value); // Updated value here
    });
  }

  render() {
    return(
      <div>
        Hello {this.props.name}
        <input type="text" onChange={this.handleClick}/>
        {this.state.value}// no value
      </div>
    );
  }
}

Upvotes: 1

Henrik Andersson
Henrik Andersson

Reputation: 47172

React in ES6 removed auto binding of this which means that functions declared on a class that extends React.Component must either .bind(this) explicitly or use arrow function syntax.

<input type="text" onChange={this.handleClick.bind(this)} />

or

class App extends React.Component {
   handleClick = (e) => {}
}

Upvotes: 5

Related Questions