React efficient way to bind event to many dom elements

Because we add onClick handlers directly to components… eg:

<button onClick={dosomething}>Click</button>

Is there an efficient way to do this (not adding an onClick to every element) when we’re dealing with dozens of elements ?

For example, in my backbone apps I would just apply a handler to a class:

events:
 'click .someclass': 'doSomething'

The backbone way seems much cleaner and easier to manage. Is there a way to emulate this behavior with React Components?

To add some perspective, I have say a dozen or more form elements that when any of them are changed, I want to potentially runs some logic. They could be text boxes, radio buttons, etc.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This optimization is not needed. It would if you were coding in other libraries like jQuery, but React does this automatically for you.

I quote:

Event delegation: React doesn’t actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React’s event handlers are simple no-ops. To learn more about why this is fast, see David Walsh’s excellent blog post.

Seen here: https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html

Method 2

You can apply the event handler to a common parent element instead and handle the event there:

<form onChange={this.handleChange}>
  {/* ...form elements... */}
</form>

…where the event handler determines what to do based on the event object’s .target:
handleChange(e) {
  this.setState({[e.target.name]: e.target.value})
}

As a live example, I have an <AutoForm> component which uses this technique to render a <form> which handles extracting data from changed fields and the submitted form for you.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x