React Fundamentals

Learn React from scratch including components, JSX, props, and state basics.

beginner Frontend Frameworks 5 hours

Chapter 7: Event Handling

Chapter 7 of 15

Chapter 7: Event Handling

7.1 Handling Events

React handles events using SyntheticEvent, a cross-browser wrapper around native events.

function Button() {
    const handleClick = () => {
        alert('Button clicked!');
    };
    
    return <button onClick={handleClick}>Click me</button>;
}

// Inline handler
function Button() {
    return (
        <button onClick={() => alert('Clicked!')}>
            Click me
        </button>
    );
}

Event Handler Naming:

  • Use handle prefix: handleClick, handleSubmit
  • Or on prefix: onClick, onSubmit
  • Pass function reference, not call result
// Correct: Pass function reference
<button onClick={handleClick}>Click</button>

// Wrong: Calls function immediately
<button onClick={handleClick()}>Click</button>

// Correct: Inline arrow function
<button onClick={() => handleClick()}>Click</button>

7.2 Event Object

Event handlers receive SyntheticEvent object with event information.

function Input() {
    const handleChange = (e) => {
        console.log('Value:', e.target.value);
        console.log('Event type:', e.type);
    };
    
    const handleKeyPress = (e) => {
        if (e.key === 'Enter') {
            console.log('Enter pressed');
        }
    };
    
    return (
        <input 
            onChange={handleChange}
            onKeyPress={handleKeyPress}
        />
    );
}

7.3 Common Events

React supports all standard DOM events.

// Mouse events
<div 
    onClick={handleClick}
    onDoubleClick={handleDoubleClick}
    onMouseEnter={handleMouseEnter}
    onMouseLeave={handleMouseLeave}
>

// Form events
<input 
    onChange={handleChange}
    onFocus={handleFocus}
    onBlur={handleBlur}
    onSubmit={handleSubmit}
/>

// Keyboard events
<input 
    onKeyDown={handleKeyDown}
    onKeyUp={handleKeyUp}
    onKeyPress={handleKeyPress}
/>

7.4 Preventing Default Behavior

Prevent default browser behavior when needed.

function Form() {
    const handleSubmit = (e) => {
        e.preventDefault(); // Prevent form submission
        // Handle form data
    };
    
    return (
        <form onSubmit={handleSubmit}>
            <input type="text" />
            <button type="submit">Submit</button>
        </form>
    );
}