If you’re wondering how to create event listeners in React (and I assume you are) then you’re in for a pleasant surprise – it is surprisingly simple. Here I’ll show you how to add event listeners to React components.
To add an event listener to a React component, first write the handler function, then attach it to an event on the component. Events in React are camelCased, so instead of the HTML attribute of onclick
, we would use onClick
in React. You may either use a named function or a function expression for the event handler. We will typically name the handler something like handleClick
or handleSubmit
, as a complement to onClick
and onSubmit
.
// Named event handler
const ClickableButton = () => {
const handleClick = () => console.log('Button got clicked!');
return ;
};
// Anonymous Event Handler
const ClickableButton = () => {
return ;
};
Below is the same example as above, only using class-based components.
// Named Event Handler
class ClickableButton extends React.Component {
handleClick() {
console.log('Button got clicked!');
}
render() {
return
}
}
// Anonymous Event Handler
class ClickableButton extends React.Component {
render() {
return
}
}