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
<button onClick={() => alert('Button clicked')}>Click me</button>
Named function reference
const handleClick = () => {
alert('Button clicked');
};
<button onClick={handleClick}>Click me</button>
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.
const handleSubmit = (event) => {
event.preventDefault();
alert(`You searched for: ${event.target.query.value}`);
};
<form action="/search" onSubmit={handleSubmit}>
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
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:
const SearchForm = () => {
return (
<form action="/search">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
);
};
<SearchForm onSubmit={handleSubmit} />
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.
const SearchForm = (props) => {
return (
<form action="/search" onSubmit={props.onSubmit}>
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
);
};
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.
const SearchForm = (props) => {
return (
<form action="/search" onSubmit={props.onSearch}>
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
);
};
const handleSearch = (event) => {
event.preventDefault();
alert(`You searched for: ${event.target.query.value}`);
};
<SearchForm onSearch={handleSearch} />
Last updated
Was this helpful?