Michał Niemiec
Michał Niemiec

Reputation: 3

es6 classes and react component methods

I'm workin with react components and es6. How should I use logic from onChange method into other method?

render() {
    let input;
    return (
<tr>  <input 
        ref = {node => { input = node; }} 
        onChange = { event => {
            if (input.value === this.props.word.pl) 
                event.currentTarget.style.backgroundColor = 'Chartreuse';
            else if (input.value !== this.props.word.pl)
                event.currentTarget.style.backgroundColor = 'LightCoral';
            else if (input.value === "")
                event.currentTarget.style.backgroundColor = 'none';
            }
        }/>

Upvotes: 0

Views: 1968

Answers (2)

vedran
vedran

Reputation: 1118

Leo, gave you an example of how to bind your methods in the constructor. But I will give you one more example on how can you avoid binding in the constructor.

Arrow functions syntax:

handleChange = e => { ... }

Upvotes: 2

Lyubomir
Lyubomir

Reputation: 20027

  1. Move your function out on a component level

  2. Bind this in the constructor

  3. Use it on multiple onChange events


class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    // bind this
    this.handleChange = this.handleChange.bind(this);
  }

  // reusable function
  handleChange(e) {
    // ... your logic for onChange here
  }

  render() { 
    return (
      <div>
        <input onChange={this.handleChange} />
        <input onChange={this.handleChange} />
      </div>
    );
  }
};

Read more about React forms here.

Upvotes: 3

Related Questions