0
0
Reactframework~5 mins

Synthetic events in React

Choose your learning style9 modes available
Introduction

Synthetic events let React handle events in a simple and consistent way across all browsers.

When you want to respond to user clicks on buttons or links.
When you need to handle keyboard input like typing or pressing keys.
When you want to track mouse movements or hover states.
When you want to handle form submissions or input changes.
When you want to listen to touch events on mobile devices.
Syntax
React
function handleClick(event) {
  // event is a SyntheticEvent
  console.log(event.type);
}

<button onClick={handleClick}>Click me</button>
React wraps native browser events into SyntheticEvent objects for consistency.
Synthetic events work the same across all browsers, so you don't worry about differences.
Examples
This example shows a simple click event handler that shows an alert.
React
function handleClick(event) {
  alert('Button clicked!');
}

<button onClick={handleClick}>Click me</button>
This example logs the current value of a text input when it changes.
React
function handleChange(event) {
  console.log('Input value:', event.target.value);
}

<input type="text" onChange={handleChange} />
This example detects when the Enter key is pressed inside an input.
React
function handleKeyDown(event) {
  if (event.key === 'Enter') {
    alert('Enter key pressed');
  }
}

<input onKeyDown={handleKeyDown} />
Sample Program

This React component shows how synthetic events work for a button click and input change. It updates a message below based on the event.

React
import React, { useState } from 'react';

export default function SyntheticEventExample() {
  const [message, setMessage] = useState('');

  function handleClick(event) {
    setMessage(`Clicked button with event type: ${event.type}`);
  }

  function handleInputChange(event) {
    setMessage(`Input changed to: ${event.target.value}`);
  }

  return (
    <main>
      <button onClick={handleClick} aria-label="Click me button">Click me</button>
      <input type="text" onChange={handleInputChange} aria-label="Type something" />
      <p>{message}</p>
    </main>
  );
}
OutputSuccess
Important Notes

Synthetic events are pooled for performance, so you cannot use them asynchronously unless you call event.persist().

Always use event.target to get the element that triggered the event.

Summary

Synthetic events make event handling consistent across browsers.

They wrap native events and provide the same interface.

Use them by attaching handlers like onClick, onChange, onKeyDown in React components.