Dom
Dom

Reputation: 695

How to attach event listener to multiple elements in React (not in-line)?

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>
    )
}

Upvotes: 1

Views: 1420

Answers (2)

Bruno Anken
Bruno Anken

Reputation: 35

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.

Upvotes: 0

0xc14m1z
0xc14m1z

Reputation: 3725

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>
    )
}

Upvotes: 1

Related Questions