How to create events in React

What are events in React?

Every web application tends to have user interaction. These interactions are made through events. An event is a type of action that can be triggered by a user or a system-generated event, for example, a mouse click, page loading, and other interactions.

Just like DOM events, React has its own event handling system known as SyntheticEventsA cross-browser wrapper around the browser’s native event. . These event handlers will be passed instances of SyntheticEvent

There are some syntax differences between DOM events and React events:

  • React events are named in camelCase (like onClick), rather than all lowercase.

  • The event listener or event handler is a function surrounded by curly brackets, as opposed to HTML, where the event handler or event listener is a string.

For example, in HTML, we do something like the following:

<button onclick="displayMessage()">
Hello World!
</button>

It is slightly different in React:

<button onClick={displayMessage}>  
Hello World!
</button>

Another distinction is that in React, you cannot return false to prevent the default behavior. You must explicitly call preventDefault. Now let's see an example of opening a page from a link by default in HTML:

<a href="#" onclick="console.log('You clicked the link.');
return false">
Click
</a>

Let's have a look at how we can do this in a React application:

function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('You clicked the link.');
}
return (
<a href="#" onClick={handleClick}>
Click
</a>
);
}
export default ActionLink;

Creating events

Let's see an example of how to create events in React. We will use the onClick event handler for this purpose:

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

Explanation

We have created an inline functionA function or a method that is declared within the onClick event inside the render method. Our React class component is created by extending the Component class, and an onClick event handler to handle the click.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved