Event Handler Naming Conventions

Here’s how the React docs describe the naming convention of event handlers

const MoviePlayer = ({ children }) => {
  const handleClick = () => {
    window.alert('you are playing a movie!');
  };

  return <button onClick={handleClick}>{children}</button>;
};

handleClick is the name of the function that is passed to the onClick jsx prop.

However, let’s say you don’t declare the event handler in the function but it is instead passed as a prop. In that case, onClick gets the name of the prop.

const MyButton = ({ children, onClick }) => {
  return <button onClick={onClick}>{children}</button>;
};

const App = () => {
  const handleClick = () => {
    window.alert('you are playing a movie!');
  };

  return <MyButton onClick={handleClick}>Play Movie</MyButton>;
};

In this case, it’s a common mistake to call the prop handleClick since that is what App passes to MyButton. However, MyButton’s notion of the function is just a prop. If the event handler is a prop, keep the onBlahBlah nomenclature.

What about if the child component needs to adjust the event handler that gets passed to it? In some cases, this is true if you want to simplify interfacing with the child component. For example:

const MyInput = ({ onValueChange, label, value }) => {
  const handleChange = (event) => {
    onValueChange(event.target.value);
  };

  return (
    <label>
      {label}
      <input value={value} onChange={handleChange} />
    </label>
  );
};

const App = () => {
  const [favoriteColor, setFavoriteColor] = useState('');

  return (
    <MyInput
      value={favoriteColor}
      label="What is your favorite color?"
      onValueChange={setFavoriteColor}
    />
  );
};

The receives a function as a prop so it should still be onBlahBlah. I could have named it onChange. But it’s probably better to be more specific. In this case, it is the value of the input that is changing so we can name it more specifically, which also helps with readability.

This may feel a little od since MyInput is the component with the handle and App doesn’t have a handle at all. But again, it’s just that a function declared should be called handle and a prop that is a function should be on. App could easily have a handle function itself in this example.

const App = () => {
  const [favoriteColor, setFavoriteColor] = useState('');

  const handleFavoriteColorChange = (color) => {
    setFavoriteColor(color)
    window.localStorage.setItem('favColor', color)
  } 

  return (
    <MyInput
      value={favoriteColor}
      label="What is your favorite color?"
      onValueChange={setFavoriteColor}
    />
  );
};

Previously, the “handle” was implicit - it just set state. Now we do a couple things when the value changes - and it is conveniently combined into a single function called handleFavoriteColorChange.

See react docs for more.