Event Handling in React: Beginner's Guide

1 min read 262 words

Responding to user events is a crucial part of building interactive UIs. In React, you can pass event handlers as props to components to run code when events occur.

Let’s look at how to listen and react to common events in React:

Binding to Events

Pass an event handler function to a component to subscribe to events:

function Button({ onClick }) {
  return (
    <button onClick={onClick}>
      Click Me
    </button>
  );
}

function App() {
  const handleClick = () => {
    console.log('Clicked!');
  };

  return (
    <Button onClick={handleClick} />
  );
}

When the button is clicked, handleClick will be called.

Event Object

Inside an event handler, you can access the native browser event via event:

const handleChange = (event) => {
  console.log(event.target.value);
}

<input onChange={handleChange} />

event contains properties like target to reference the DOM element.

Supported Events

You can listen to common events like:

  • onClick
  • onSubmit
  • onChange
  • onKeyDown
  • onScroll

And many more. Refer to React’s SyntheticEvent docs for the full list.

Event Handler Scope

Make sure handlers are properly scoped to access component props and state:

// Won't work!
function App() {
  const [text, setText] = useState('');
  
  return (
    <input 
      onChange={(e) => setText(e.target.value)} // no text
    />
  );
}

// Bind handler instead
function App() {
  const [text, setText] = useState('');

  const updateText = (e) => setText(e.target.value);
  
  return (
    <input
      onChange={updateText} 
    />
  );
}

Summary

  • Pass event handlers as props to listen for events
  • Access the browser event object via event
  • Use common events like onClick and onChange
  • Bind component methods to avoid scoping issues

Mastering events allows building highly interactive React interfaces.

Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts