In ReactJS, there are events by which user uses to interact with an application UI. React listens to events at the document level, after receiving events from the browser, React wraps these events with a wrapper that has a similar interface as the local browser event, which helps us to use methods like preventDefault().
Why use such a wrapper?
So, often we use different browsers where the same event has different names. Here wrapper does is triggering all the different names for the same event effect. Therefore, whenever we are triggering an event in a ReactJS, we are not actually trying to trigger the real DOM event, instead, we are using the ReactJS custom event type, which is the synthetic event.
The examples of the synthetic events are onClick(), onBlur() and onChange(). These all are not real DOM events but react synthetic events.
Benefits of using synthetic events:
- Cross browsers applications are easy to implement.
- Synthetic events are that ReactJS reuses these events objects, by pooling them, which increase the performance.
Let’s look at an example of a ReactJS application using synthetic events.
Creating React Application
Step 1: Create a React application using the following command:
npx create-react-app example
Step 2: After creating your project folder i.e. example, move to it using the following command:
cd example
Project structure: It will look like this.
Example: Write down the following code in the index.js and App.js files.
Javascript
//index.js import React from 'react' ; import ReactDOM from 'react-dom' ; import './index.css' ; import App from './App' ; import reportWebVitals from './reportWebVitals' ; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById( 'root' ) ); reportWebVitals(); |
Javascript
//App.js import React from "react" ; function App() { function handleClick() { alert( "You clicked me!" ); } return ( <div style={{ display: "flex" , alignItems: "center" , justifyContent: "center" , height: "100vh" }}> <button onClick={() => { handleClick() }}>show alert </button> </div> ); } export default App; |
Step to run the application: Run the application using the following command:
npm start
Output: The alert event is wrapped with onClick synthetic event.
This way we use synthetic events a lot in our application based on ReactJS.