React - Events

Events

React normalizes browser events into a consistent API.

Try it: Toggle

View source
const { useState } = React;
function Toggle(){
  const [on, setOn] = useState(false);
  return (
    <div>
      <button onClick={() => setOn(o => !o)}>{on ? 'ON' : 'OFF'}</button>
      {on && <p style={{marginTop:8}}>The switch is ON.</p>}
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('try-events')).render(<Toggle />);

Syntax primer (for newcomers)

  • onClick attribute takes a function: onClick={() => ...}.
  • Use the updater form setOn(o => !o) when you derive the next state from previous state.

Common pitfalls

  • Don’t call the function directly in JSX like onClick=setOn(true); pass a function instead.
  • Event handlers are camelCase: onChange, onSubmit.

Vocabulary

  • Event: A browser interaction (click, change, submit) normalized by React.
  • Handler: A function you pass to props like onClick to respond to events.

Checks for Understanding

  1. Why should event handlers be passed as functions and not executed inline?
  2. When should you prefer the updater form like setOn(o => !o)?
Show answers
  1. Executing inline runs immediately during render; passing a function defers it until the event fires.
  2. When the next state depends on the previous state to avoid stale values.

Exercises

  1. Add a keyboard handler: toggle the switch when the user presses Enter inside the component.
  2. Create a form with an input and a submit button; use onSubmit and preventDefault() to show the typed text without reloading.
  3. Disable the toggle button for 1s after it’s clicked; re-enable it with setTimeout to practice timing and state.