Does it need to be a component?
Share markup with a plain function, and know when that stops being enough.
This scoreboard draws two cards that look the same, one per team, and writes the markup out twice. After the last two lessons it is tempting to reach for a TeamCard component.
Predict
Read Scoreboard.ts. Suppose you made the card a component, like Counter in the last lesson. What would its Model hold?
Check your answer
Nothing. Both scores are in the Scoreboard's Model, and they have to be: New game clears the two of them at once. A card draws a name and a number it is given, and reports a click.
A component with an empty Model is a loop with nothing to fold.
Try it
Add a plain function above the component, and build both cards with
Card(h).children(...).Carddoesn't call.childrenitself. Who does?
const Card = <M>(h: Html.H<M>) => h.section.class("card stack")Now the whole card. Before you read the code below: the button needs a click handler. What kind of thing do you pass for it?
const TeamCard = <M>(h: Html.H<M>, options: {
readonly name: string
readonly score: number
readonly onScore: M
}) =>
Card(h).children(
h.span.class("muted").children(options.name),
h.strong.class("big").children(String(options.score)),
h.button.on("click", options.onScore).children("Score")
)Replace both cards in
viewwithTeamCard(h, { ... }), passingScoreboardMessage.ClickedScore({ team: "home" })asonScorefor the first. Run, then press Score. Before you look at the log: will the rows carry a new path, as they did with two counters?When would this piece have to become a component after all?
About steps 3 and 4
No new path. A function adds no instance, so the rows are still the Scoreboard's own messages. Nothing about the loop changed. Only the text of view did.
It becomes a component on the day it needs state that nobody outside decides, such as a card that remembers whether its details are open, or work of its own to run.
What you found
Lesson 9 said the screen is a function of state. So a piece of the screen is a function too. A view function takes h, typed Html.H<M> for a component whose messages are M, plus whatever it should draw, and returns elements.
The handler went in like the name and the score, because in lesson 11 a click handler stopped being a callback and became a value. There is nothing to wire up and nothing to keep in step.
So the question to ask of a piece is whether it has state of its own. If it does, it is a component. If it only draws what it is handed, it is a function.
Functions and components both get what they need as arguments. A Command needs things of another kind: a server, a clock, a translator. Where does a component get what it needs?
Reach for a function first
A component is for state. Markup you want to reuse is a function that takes h and returns elements.