</>
Skip to content
React lessons (12/47)

React — Events

Basic Event Handling

function Button() {
    const handleClick = () => {
        alert('Button clicked!');
    };

    return <button onClick={handleClick}>Click Me</button>;
}

Event with Parameters

function UserList({ users }) {
    const handleDelete = (id) => {
        console.log('Delete user:', id);
    };

    return (
        <ul>
            {users.map(user => (
                <li key={user.id}>
                    {user.name}
                    <button onClick={() => handleDelete(user.id)}>
                        Delete
                    </button>
                </li>
            ))}
        </ul>
    );
}

Event with Event Object

function Input() {
    const handleChange = (e) => {
        console.log('Value:', e.target.value);
    };

    return <input onChange={handleChange} />;
}

Common Events

// Click event
<button onClick={handleClick}>Click</button>

// Change event
<input onChange={handleChange} />

// Submit event
<form onSubmit={handleSubmit}>...</form>

// Mouse events
<div onMouseEnter={handleMouseEnter}>
<div onMouseLeave={handleMouseLeave}>

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

Event Examples

// Form submission
function LoginForm() {
    const handleSubmit = (e) => {
        e.preventDefault();
        console.log('Form submitted');
    };

    return (
        <form onSubmit={handleSubmit}>
            <input type="text" />
            <button type="submit">Login</button>
        </form>
    );
}

// Keyboard input
function SearchBox() {
    const handleKeyPress = (e) => {
        if (e.key === 'Enter') {
            console.log('Search:', e.target.value);
        }
    };

    return <input onKeyPress={handleKeyPress} />;
}

// Mouse hover
function HoverCard() {
    const [isHovered, setIsHovered] = useState(false);

    return (
        <div
            onMouseEnter={() => setIsHovered(true)}
            onMouseLeave={() => setIsHovered(false)}
            className={isHovered ? 'hovered' : ''}
        >
            Hover over me!
        </div>
    );
}

Mini Practice

Write React code that:

  1. Handles click events
  2. Handles form submission
  3. Handles keyboard events
  4. Handles mouse hover events

Up Next

Next: Learn about Conditional Rendering.

Related Topics

Frequently Asked Questions about Events

What is Events in React?

Events is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Events?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Events.

Why is Events important in React?

Events is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.