requiem
requiem

Reputation: 33

Reactjs which is the better way to use change handler

So I know there are several ways to do this but I am wondering which is the better or more appropriate way to create a search bar component? Could you please explain why? I'm new to react and have seen tutorials and what not and everybody does there change handlers a little differently.

state = {
 term: '',
};

onChange = this.onChange.bind(this);

onChange(e) {
 console.log(e.target.value);
 this.setState({ term: e.target.value });
};

<input
 value={this.state.term}
 onChange={this.onChange}
/>

I feel this way could be better because it allows you to reuse the onChange handler for several different states.

state = {
 term: '',
};

onChange = name => e => {
 this.setState({ [name]: e.target.value });
};

<input
 value={this.state.term}
 onChange={this.onChange('term')}
/>

Upvotes: 2

Views: 288

Answers (1)

CodeZombie
CodeZombie

Reputation: 2087

In order to reuse the onChange handler, the below code would be more appropriate and better too.

onChange = e => {
 this.setState({ 
    [e.target.name]: e.target.value 
 });
};

<input type="text" name="name" onChange={(e)=>this.onChange(e)} />

Upvotes: 2

Related Questions