← React Beginner Questions - Set 5 Q47

How do you handle events in React?

React Beginner Questions - Set 5

Handlers are functions passed as props, with a synthetic event that normalises browser differences.

Example

export default function Toolbar({ onSave, items }) {
  function handleDelete(id, event) {
    event.stopPropagation();          // do not bubble to the row
    console.log('delete', id);
  }

  return (
    <div onClick={() => console.log('row clicked')}>
      <button onClick={onSave}>Save</button>
      <button onClick={e => handleDelete('all', e)}>Delete all</button>
      {items.map(i => (
        <button key={i.id} onClick={e => handleDelete(i.id, e)}>{i.name}</button>
      ))}
    </div>
  );
}

What to notice

← Back to the question list