Lesson 4 • Beginner

    Handling Events ⚛️

    Respond to user interactions — clicks, key presses, form submissions, and more — the React way.

    What You'll Learn in This Lesson

    • • React's event system (SyntheticEvent)
    • • Handling click events and passing arguments
    • • The event object and preventDefault()
    • • Input events with onChange
    • • Keyboard and mouse event patterns

    1️⃣ Click Events

    React events use camelCase naming (onClick not onclick) and accept a function reference, not a string. This is one of the key differences from HTML event handling.

    Try It: Click Events

    Handle clicks and pass arguments to event handlers

    Try it Yourself »
    JavaScript
    // Click Events in React
    console.log("=== Handling Click Events ===");
    console.log();
    
    // Basic click handler
    console.log("// Basic button click:");
    console.log("function App() {");
    console.log("  function handleClick() {");
    console.log("    alert('Button clicked!');");
    console.log("  }");
    console.log("  return <button onClick={handleClick}>Click Me</button>;");
    console.log("}");
    console.log();
    
    // React vs HTML events
    console.log("=== React vs HTML Events ===");
    console.log("HTML:   onclick='ha
    ...

    2️⃣ The Event Object

    React wraps native browser events in SyntheticEvent objects for cross-browser compatibility. Use e.preventDefault() for forms and e.stopPropagation() to prevent bubbling.

    Try It: Event Object

    Explore SyntheticEvent properties and preventDefault

    Try it Yourself »
    JavaScript
    // The Event Object
    console.log("=== React's SyntheticEvent ===");
    console.log("React wraps browser events in SyntheticEvent for cross-browser compatibility.");
    console.log();
    
    // Common event properties
    console.log("=== Common Event Properties ===");
    const eventProps = [
      ["e.target", "The element that triggered the event"],
      ["e.target.value", "Value of input/select element"],
      ["e.currentTarget", "Element the handler is attached to"],
      ["e.preventDefault()", "Prevent default browser behav
    ...

    3️⃣ Input Events

    The onChange event fires whenever an input value changes. Combined with state, this creates controlled components where React is the single source of truth for form data.

    Try It: Input Events

    Track input changes and handle multiple form fields

    Try it Yourself »
    JavaScript
    // Input Events — onChange, onFocus, onBlur
    console.log("=== Tracking Input Changes ===");
    console.log();
    
    // onChange for text inputs
    console.log("function SearchBar() {");
    console.log("  const [query, setQuery] = useState('');");
    console.log();
    console.log("  return (");
    console.log("    <input");
    console.log("      type='text'");
    console.log("      value={query}");
    console.log("      onChange={(e) => setQuery(e.target.value)}");
    console.log("      placeholder='Search...'");
    console.log("    /
    ...

    4️⃣ Keyboard & Mouse Events

    Beyond clicks, React supports keyboard events (onKeyDown), mouse events (onMouseEnter), and more. Event delegation lets you handle events on a parent instead of attaching handlers to every child.

    Try It: Keyboard & Mouse

    Handle keyboard shortcuts and mouse interactions

    Try it Yourself »
    JavaScript
    // Keyboard & Mouse Events
    console.log("=== Keyboard Events ===");
    console.log();
    
    console.log("onKeyDown  → Fires when a key is pressed down");
    console.log("onKeyUp    → Fires when a key is released");
    console.log("onKeyPress → Deprecated (don't use)");
    console.log();
    
    console.log("// Example: Submit on Enter key");
    console.log("function ChatInput() {");
    console.log("  function handleKeyDown(e) {");
    console.log("    if (e.key === 'Enter' && !e.shiftKey) {");
    console.log("      e.preventDefault(
    ...

    ⚠️ Common Mistakes

    ⚠️
    Calling function immediatelyonClick={handleClick()} calls it on render. Use onClick={handleClick}.
    ⚠️
    Forgetting preventDefault — Forms will reload the page without e.preventDefault().
    💡
    Pro Tip: Name handlers descriptively: handleSubmit, handleDelete, handleSearchChange — not just handler or onClick.

    📋 Quick Reference

    EventUsage
    onClick<button onClick={fn}>Click</button>
    onChange<input onChange={(e) => set(e.target.value)} />
    onSubmit<form onSubmit={handleSubmit}>
    onKeyDowne.key === 'Enter'
    With argsonClick={() => fn(id)}

    🎉 Lesson Complete!

    You can now handle any user interaction in React. Next, we'll deep-dive into the most important hooks: useState and useEffect!

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service