Open In App

Why is the use of Synthetic Events in ReactJS ?

Last Updated : 09 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

React uses Synthetic Events with the purpose to wrap native events of the browser. For various performance reasons, synthetic Events are wrapped and reused across multiple native events of the different browsers. ReactJS implements a synthetic events system because that brings consistency and high performance to React apps and application UI. It helps to achieve consistency by normalizing native events so that they have the same properties across different browsers and platforms. 

What are the major reasons?

  • Cross-browser Support: It wraps the browser’s native event through the native Event attribute and provides a uniform API and consistent behavior on the top node level.
  • Application Better performance: Events are delegated to document through bubbling.

Let’s create an app and take a look at how Synthetic Events gives cross-browser support.

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.

folder structure

Example: Write down the following code in index.js, App.js. As we know there is no onClick() native event. We will implement it and test it on different browsers.

Filename: index.js

Javascript




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')
);
  
// If you want to start measuring performance
// in your app, pass a function to log results
reportWebVitals();


Filename: App.js

Javascript




import React from 'react';
  
function App() {
  function handleClick() {
    alert('You clicked me!');
  }
  
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        height: '100vh',
      }}>
      <button
        style={{
          backgroundColor: 'red',
          color: 'white',
          fontSize: '2rem',
          padding: '1rem',
          borderRadius: '5px',
          cursor: 'pointer',
        }}
        onClick={() => {
          handleClick();
        }}>
        show alert{' '}
      </button>
    </div>
  );
}
  
export default App;


Step to run the application: Run the application using the following command:

npm start

Output: Now, open the URL http://localhost:3000/ in a different browser and check compatibility.

  • In chrome:

chrome output

  • In firefox:

firefox output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads