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.
How do you handle multiple events in React? Call a Function onClick in React The first solution to perform multiple onClick events in React is to include all of your actions inside of a function and then call that single function from the onClick event handler.
Avoid binding by using the public class fields syntax, or bind your callbacks inside the constructor.
Bind with the Arrow Function This approach is probably the best way of doing bindings. It's simple, easy to read, and most importantly, it works.
When you add an onClick prop to the LinkButton component, it is just a property of an object. By calling props. onClick from inside of that component you are just calling a function that is stored inside of a property, similar to this: let props = { onClick: function () { alert("Executed!"); } }; props.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With