Reputation: 695
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
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
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