Events
In React, we add event handlers directly on a JSX element instead of using addEventListener
using camelCased on*
event attributes (i.e. onClick
, onSubmit
). The attribute value is the event handler and can either be an inline function or a reference to a named function.
Inline function
Named function reference
Event Object
Like in native JavaScript, event handlers in React also get passed an event object. This event object, however, is a SyntheticEvent
object and not the native event object. The differences are few and subtle, we can treat the SyntheticEvent
object as we would the native event object.
React's SyntheticEvent
is a cross-browser wrapper around native events which ensures events work identically across supported browsers.
Events and Custom Components
Event handlers will only work on JSX tags. They won't work on custom React components.
This won't work as the onSubmit
needs to be added to the form
JSX tag:
In order for handleSubmit
to work, we need to add the event handler to the form
tag itself. The handleSubmit
function is being passed to the SearchForm
component as a prop named onSubmit
so we already have a reference to the event handler we want.
Naming Conventions
In JSX tags, the attributes onClick
, onSubmit
, etc. are the actual event names so we can't change that. But, when we pass event handlers as props to custom components, we can give those different names.
Last updated
Was this helpful?