CARVIEW |
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 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 render
method. Our React class component is created by extending the Component
class, and an onClick
event handler to handle the click.
Relevant Answers
Explore Courses
Free Resources