securenai securenai - 1 year ago 114
React JSX Question

HTML event handler vs React event handler

I would like to ask a question about event handlers when used in HTML and React.

In the book Javascript and Jquery written by Jon Duckett, the author mentioned that using HTML event handler attribute is considered bad practice
for instance something like the following:

<button onClick="hide()">click me</button>

But recently I am starting to learn React and when a component is defined, there are many examples of event handlers used as an attribute and it seems common to do so, not getting criticism for doing so,

<button onClick={doSomething}>

Is there a reason to this? is it because this is the only way to bind a event handler in React?, from the way I see it React is essentially building the component element via HTML but uses the event handler attribute to assign an event to it,
so why is React bringing back a concept that is considered bad practice?

Answer Source

Why are inline event listeners bad practice?

HTML describes the content and structure of a document, CSS describes the appearance and JavaScript is about the logic or behavior. These things should be kept separately. HTML and JavaScript code shouldn't be mixed. Your example for that was:

<button onClick="hide()">click me</button>

This, however, does not apply to React: we don't have one HTML file. Instead, we have modularized components, which have their own structure, style and behavior.

In React, we don't want the separation of presentation and logic, but self-contained components. That's what sets it apart from an application using just "Vanilla JavaScript" / the DOM API.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download