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)
- onClickattribute 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 onClickto respond to events.
Checks for Understanding
- Why should event handlers be passed as functions and not executed inline?
- When should you prefer the updater form like setOn(o => !o)?
Show answers
- Executing inline runs immediately during render; passing a function defers it until the event fires.
- When the next state depends on the previous state to avoid stale values.
Exercises
- Add a keyboard handler: toggle the switch when the user presses Enter inside the component.
- Create a form with an input and a submit button; use onSubmitandpreventDefault()to show the typed text without reloading.
- Disable the toggle button for 1s after it’s clicked; re-enable it with setTimeoutto practice timing and state.