6

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.

4
  • From a code perspective, i see what you mean, but i wonder if react does this under the hood as an optimization. Commented May 22, 2015 at 15:15
  • If you are applying a class to something, how is it more difficult to apply an onClick handler? Im not sure what you are hoping to achieve Commented May 22, 2015 at 15:25
  • Fair point @LukeMcGregor. I guess I'm just not used to these inline handlers. feels strange. Commented May 22, 2015 at 23:23
  • The handler shouldn't really be inline, you just pass a function ref to the onclick, I spouse that kinda feels more inline than a jQuery click bind style Commented May 23, 2015 at 0:08

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.