rksh
rksh

Reputation: 4050

Accessing state values in React Component

I'm somewhat new to reactjs. In React.createclass element you can access an input value or any state value such as this

  change: function(e) {
    this.setState({author: e.target.value});
  },

However in React.component this is not possible, so how can I achieve the similar task in React.component

Thanks

Upvotes: 2

Views: 2709

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77482

If you want to pass methods to event handlers like this onChange={ this.change } and use ES2015 classes, you have to set this for these methods by yourself, for example

class App extends React.Component {
  constructor() {
    super();
    this.state = { author: '' };
    this.change = this.change.bind(this); // set this for change method
  }

  change(e) {
    this.setState({ author: e.target.value });
  }

  render() {
    return <input onChange={ this.change } value={ this.state.author } /> 
  }
}

Example

Upvotes: 3

Related Questions