← Back to the exercise

Passing handlers down

The answer to the exercise in Passing handlers down.

  • App passed play and ShowCard reads onPlay. Those are two different props, so every Play button was handed undefined.
  • onWatched() ran while React was drawing each card, which is why the console filled up before any click. Passing onWatched on its own leaves it for React to call later.
import "./styles.css";
import ShowCard from "./ShowCard";

export default function App() {
  function handlePlay(title) {
    alert("Playing " + title);
  }

  function handleWatched(title) {
    console.log("Watched " + title);
  }

  return (
    <div className="page">
      {/* was: play={() => handlePlay("The Bear")} */}
      <ShowCard
        title="The Bear"
        year={2022}
        genre="Drama"
        rating={8.6}
        still="still-warm"
        onPlay={() => handlePlay("The Bear")}
        onWatched={() => handleWatched("The Bear")}
      />
      <ShowCard
        title="Severance"
        year={2022}
        genre="Thriller"
        rating={8.7}
        still="still-cold"
        onPlay={() => handlePlay("Severance")}
        onWatched={() => handleWatched("Severance")}
      />
      <ShowCard
        title="Andor"
        year={2022}
        genre="Sci-Fi"
        rating={8.4}
        still="still-dusty"
        onPlay={() => handlePlay("Andor")}
        onWatched={() => handleWatched("Andor")}
      />
    </div>
  );
}