SimianAngel SimianAngel - 2 months ago 6
React JSX Question

What are the advantages of using onClick in React components over jQuery's .on("click") method?

Recently I've been working on a task management project with dependencies that include both React and jQuery. Users can view a daily list of dynamically-added tasks, which are either loaded from a remote server via AJAX or created by the user via a "new task" control. The list of tasks is rendered into a parent

element that exists within an HTML page.

Here are some possible actions that a user can take on a task:

  • Edit the task's description

  • Add notes regarding actions taken on the task

  • Mark the task as completed

  • Re-schedule the task to a new due date

Each action is initiated by clicking its corresponding
element. When performing these actions, users can either confirm their action to commit the change or cancel and revert to the original state of the task. These confirm and cancel controls are also triggered by clicking buttons.

All in all, each task contains as many as 12 button controls, and thus adds 12 click event bindings. I know I can write functions within my React component classes that will perform the action, and that I can call these functions with React by including an
attribute in the
element of my render functions:

var AddNoteConfirm = React.createClass({
handleClick: function() {
// logic to save the added note...
render: function() {
return (
<button className="addNote-confirm" onClick={this.handleClick}>
Save Note

But let's say I'm rendering 50 tasks at once. That would create 600 event bindings.

Using the
method of jQuery I would only need to perform 12 event bindings, because I can bind to the parent
container and pass a selector for a given button as an argument:

$('#task-container').on('click', '.addNote-confirm', function() {
// logic to save the added note...

As the number of event handlers is greatly reduced with this strategy, wouldn't the jQuery implementation of event handling be the better, more scalable option? Or perhaps I'm overlooking something. Are there other reasons why the React implementation would be the better solution?


React uses event delegation (like jquery.on()) in it's Synthetic Events system for the same performance issues - see Under the Hood: Autobinding and Event Delegation.

In addition the event system is an integral part of a react component. If you'll use outside event, you'll have to somehow connect it to the current component to use .setState or call a callback that came from the component's parent via props.