Handlers

Adding Event Handlers

The naming convention for handlers is typically handler then the event name

export default function Button() {
  function handleClick() {
    alert('You clicked me!');
  }

  return (
    <button onClick={handleClick}>
      Click me
    </button>
    
    // or use a lambda
    <button onClick={() => {
		  alert('You clicked me!');
		}}>
  );
}

Passing events as Props

function Button({ onSmash, children }) {
  return (
    <button onClick={onSmash}>
      {children}
    </button>
  );
}

export default function App() {
  return (
    <div>
      <Button onSmash={() => alert('Playing!')}>
        Play Movie
      </Button>
    </div>
  );
}

Event Propagation

Here pressing a button will cause the on click event to propergate up the tree, thus triggering the toolbar aswell. So in the case below by pressing a button the button alert and the toolbar alert will trigger in that order.

export default function Toolbar() {
  return (
    <div className="Toolbar" onClick={() => {
      alert('You clicked on the toolbar!');
    }}>
      <button onClick={() => alert('Playing!')}>
        Play Movie
      </button>
      <button onClick={() => alert('Uploading!')}>
        Upload Image
      </button>
    </div>
  );
}

But you can stop the bubbling up of the event like so… with the stopPropagation command.

function Button({ onClick, children }) { // <--- Notice we are passing a handler
  return (
    <button onClick={e => {
      e.stopPropagation();
      onClick();
    }}>
      {children}
    </button>
  );
}

export default function Toolbar() {
  return (
    <div className="Toolbar" onClick={() => {
      alert('You clicked on the toolbar!');
    }}>
      <Button onClick={() => alert('Playing!')}>
        Play Movie
      </Button>
      <Button onClick={() => alert('Uploading!')}>
        Upload Image
      </Button>
    </div>
  );
}