1

Instead of having to attach event listener to each element, how can you add event listeners to a group? Consider having multiple input elements. Instead of repeating onChange={this.handleChange} how can I just attach this function to onChange for all input elements?

Something that with vanilla JS was as easy as selecting all inputs, looping and attaching.

render() {
    return (
        <form>
            <input type="text" name="firstName" placeholder="First Name" onChange={this.handleChange} />
            <br />
            <input type="text" name="lastName" placeholder="Last Name" onChange={this.handleChange} />
            <h1>{this.state.firstName} {this.state.lastName}</h1>
        </form>
    )
}

2 Answers 2

1

You could create a dedicated on-the-fly component, something like:

render() {
    const Input = props =>
      <input onChange={ this.handleChange } { ...props } />

    return (
        <form>
            <Input type="text" name="firstName" placeholder="First Name" />
            <br />
            <Input type="text" name="lastName" placeholder="Last Name" />
            <h1>{this.state.firstName} {this.state.lastName}</h1>
        </form>
    )
}
Sign up to request clarification or add additional context in comments.

2 Comments

It works, thanks you. But I am guessing there is no 'vanila js' way of selecting, looping and attaching?
Nope, this is the React way, it's declarative :)
0

You could try making your elements that must be subscribed (such as the inputs in your code example) into components, creating an array object with them and .map over it, passing your handleChange function to them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.