techStackGuru

React Synthetic Events


The React library provides synthetic events that abstract the native event handling of the browser. React creates and manages synthetic events to ensure consistency across browsers. The events are synthetic because they are wrappers around native browser events, not the actual events.

Components created in React can have event listeners attached to them. In the case of a button component, you can attach a click event handler. You receive a synthetic event object when you click the button, which React passes to your event handler.

Using the event parameter provided to the handler function, you can access properties and methods of the synthetic event object.

Example

function handleClick(event) {
    console.log(event.target.value); // Accessing target value of a clicked element
  }
  
  function MyComponent() {
    return <button onClick={handleClick}>Click Me</button>; 

As shown in this example, the handleClick function is called with information about the event when the button is clicked.

React's synthetic events differ from native events in some important ways:

  • Cross-browser consistency
  • Event delegation
  • Performance optimizations
  • Asynchronous event handling
  • Here are some examples of how React uses synthetic events:

    Example: Handling a Click Event

    import React from 'react';
    
        function handleClick(event) {
          console.log('Button clicked!');
        }
        
        function MyComponent() {
          return <button onClick={handleClick}>Click Me</button>;
        } 

    Example: Handling a Change Event

    import React, { useState } from 'react';
    
        function handleChange(event) {
          const inputValue = event.target.value;
          console.log('Input value:', inputValue);
        }
        
        function MyComponent() {
          const [inputValue, setInputValue] = useState('');
        
          return (
            <input
              type="text"
              value={inputValue}
              onChange={handleChange}
            />
          );
        } 

    Example: Preventing Default Behavior

    import React from 'react';
    
        function handleLinkClick(event) {
          event.preventDefault();
          console.log('Link clicked! Default behavior prevented.');
        }
        
        function MyComponent() {
          return (
            <a href="https://api.com" onClick={handleLinkClick}>
              Click Me
            </a>
          );
        }