Skip
Arish's avatar

6. Event Handling


Event Handling in React

React provides a synthetic event system that wraps native browser events, providing consistent behavior across all browsers.

Basic Event Handling

jsx
1function Button() {
2  const handleClick = () => {
3    console.log('Button clicked!')
4  }
5  
6  return <button onClick={handleClick}>Click me</button>
7}
8
9// Inline handler (for simple cases)
10function Button() {
11  return (
12    <button onClick={() => console.log('Clicked!')}>
13      Click me
14    </button>
15  )
16}

Common Events

Mouse Events

jsx
1function MouseEvents() {
2  return (
3    <div
4      onClick={() => console.log('clicked')}
5      onDoubleClick={() => console.log('double clicked')}
6      onMouseEnter={() => console.log('mouse entered')}
7      onMouseLeave={() => console.log('mouse left')}
8      onMouseMove={(e) => console.log(e.clientX, e.clientY)}
9      onContextMenu={(e) => {
10        e.preventDefault()
11        console.log('right clicked')
12      }}
13    >
14      Hover and click me
15    </div>
16  )
17}

Keyboard Events

jsx
1function KeyboardEvents() {
2  const handleKeyDown = (e) => {
3    console.log('Key pressed:', e.key)
4    
5    if (e.key === 'Enter') {
6      console.log('Enter pressed!')
7    }
8    
9    if (e.key === 'Escape') {
10      console.log('Escape pressed!')
11    }
12    
13    // Check for modifier keys
14    if (e.ctrlKey && e.key === 's') {
15      e.preventDefault()
16      console.log('Save shortcut!')
17    }
18  }
19  
20  return (
21    <input
22      onKeyDown={handleKeyDown}
23      onKeyUp={(e) => console.log('Key released:', e.key)}
24      placeholder="Type something..."
25    />
26  )
27}

Form Events

jsx
1function FormEvents() {
2  const [value, setValue] = useState('')
3  
4  const handleSubmit = (e) => {
5    e.preventDefault()  // Prevent page reload
6    console.log('Form submitted:', value)
7  }
8  
9  return (
10    <form onSubmit={handleSubmit}>
11      <input
12        value={value}
13        onChange={(e) => setValue(e.target.value)}
14        onFocus={() => console.log('Input focused')}
15        onBlur={() => console.log('Input blurred')}
16      />
17      <button type="submit">Submit</button>
18    </form>
19  )
20}

Focus Events

jsx
1function FocusEvents() {
2  return (
3    <input
4      onFocus={() => console.log('Focused')}
5      onBlur={() => console.log('Blurred')}
6    />
7  )
8}

The Event Object

React events receive a SyntheticEvent object:

jsx
1function EventObject() {
2  const handleClick = (event) => {
3    // Event properties
4    console.log(event.type)         // 'click'
5    console.log(event.target)       // The DOM element
6    console.log(event.currentTarget)// The element with the handler
7    console.log(event.timeStamp)    // When it happened
8    
9    // Mouse position
10    console.log(event.clientX)      // X relative to viewport
11    console.log(event.clientY)      // Y relative to viewport
12    console.log(event.pageX)        // X relative to page
13    console.log(event.pageY)        // Y relative to page
14    
15    // Modifier keys
16    console.log(event.altKey)       // Alt pressed?
17    console.log(event.ctrlKey)      // Ctrl pressed?
18    console.log(event.shiftKey)     // Shift pressed?
19    console.log(event.metaKey)      // Cmd/Win pressed?
20    
21    // Prevent default behavior
22    event.preventDefault()
23    
24    // Stop propagation
25    event.stopPropagation()
26  }
27  
28  return <button onClick={handleClick}>Click me</button>
29}

Passing Arguments to Handlers

jsx
1function ItemList() {
2  const items = ['Apple', 'Banana', 'Cherry']
3  
4  // Method 1: Arrow function
5  const handleClick = (item) => {
6    console.log('Clicked:', item)
7  }
8  
9  return (
10    <ul>
11      {items.map((item, index) => (
12        <li key={index} onClick={() => handleClick(item)}>
13          {item}
14        </li>
15      ))}
16    </ul>
17  )
18}
19
20// With event object
21function Button() {
22  const handleClick = (id, event) => {
23    console.log('ID:', id)
24    console.log('Event:', event.type)
25  }
26  
27  return (
28    <button onClick={(e) => handleClick(123, e)}>
29      Click me
30    </button>
31  )
32}

Preventing Default Behavior

jsx
1function PreventDefault() {
2  const handleSubmit = (e) => {
3    e.preventDefault()  // Don't reload page
4    console.log('Form submitted!')
5  }
6  
7  const handleLinkClick = (e) => {
8    e.preventDefault()  // Don't navigate
9    console.log('Link clicked!')
10  }
11  
12  return (
13    <div>
14      <form onSubmit={handleSubmit}>
15        <button type="submit">Submit</button>
16      </form>
17      
18      <a href="https://example.com" onClick={handleLinkClick}>
19        Click me (won't navigate)
20      </a>
21    </div>
22  )
23}

Event Propagation

jsx
1function EventBubbling() {
2  const handleParentClick = () => {
3    console.log('Parent clicked')
4  }
5  
6  const handleChildClick = (e) => {
7    e.stopPropagation()  // Prevent bubbling to parent
8    console.log('Child clicked')
9  }
10  
11  return (
12    <div onClick={handleParentClick} style={{ padding: '20px', background: 'lightblue' }}>
13      Parent
14      <button onClick={handleChildClick}>
15        Child (click won't bubble)
16      </button>
17    </div>
18  )
19}

Input Events

jsx
1function InputEvents() {
2  const [text, setText] = useState('')
3  
4  return (
5    <div>
6      {/* Controlled input */}
7      <input
8        value={text}
9        onChange={(e) => setText(e.target.value)}
10      />
11      
12      {/* Different input types */}
13      <input
14        type="checkbox"
15        onChange={(e) => console.log(e.target.checked)}
16      />
17      
18      <select onChange={(e) => console.log(e.target.value)}>
19        <option value="a">Option A</option>
20        <option value="b">Option B</option>
21      </select>
22      
23      <input
24        type="file"
25        onChange={(e) => console.log(e.target.files[0])}
26      />
27    </div>
28  )
29}

Event Handler Patterns

Handler as Prop

jsx
1function Button({ onClick, children }) {
2  return (
3    <button onClick={onClick} className="btn">
4      {children}
5    </button>
6  )
7}
8
9function App() {
10  const handleSave = () => console.log('Saved!')
11  const handleDelete = () => console.log('Deleted!')
12  
13  return (
14    <div>
15      <Button onClick={handleSave}>Save</Button>
16      <Button onClick={handleDelete}>Delete</Button>
17    </div>
18  )
19}

Named Event Handlers

jsx
1function Form() {
2  const [form, setForm] = useState({ name: '', email: '' })
3  
4  // Named handler for each field
5  const handleNameChange = (e) => {
6    setForm({ ...form, name: e.target.value })
7  }
8  
9  const handleEmailChange = (e) => {
10    setForm({ ...form, email: e.target.value })
11  }
12  
13  // Or single handler for all fields
14  const handleChange = (e) => {
15    const { name, value } = e.target
16    setForm({ ...form, [name]: value })
17  }
18  
19  return (
20    <form>
21      <input name="name" value={form.name} onChange={handleChange} />
22      <input name="email" value={form.email} onChange={handleChange} />
23    </form>
24  )
25}

Touch Events (Mobile)

jsx
1function TouchEvents() {
2  return (
3    <div
4      onTouchStart={() => console.log('Touch started')}
5      onTouchMove={(e) => console.log(e.touches[0].clientX)}
6      onTouchEnd={() => console.log('Touch ended')}
7    >
8      Touch me
9    </div>
10  )
11}

Event handling is how you make React applications interactive!