JSX, Typed Props and Composition
Worked example: turn an untyped, unusable component into reusable, fully typed ones — a Badge, a Button that forwards native attributes, and a toolbar that composes them.
Contentsand lesson path
On this page
- The problem
- Step 1: the untyped version, and what the compiler says
- Step 2: a typed Badge that wraps any content
- Step 3: a Button that forwards native attributes
- Step 4: compose the toolbar
- Check your understanding
- Apply it
- Review prompt
Lessons of React Components & State
- From Mockup to Component Tree Concept · 20 min
- JSX, Typed Props and Composition Worked example · 25 min
- State, Events and Immutable Updates Worked example · 25 min
- Lists, Keys and When React Re-renders Concept · 20 min
- Lab: A Filterable, Sortable Product Table Lab · 30 min
- Check: Predict the Component Behavior Knowledge check · 6 questions
What you will learn
- Break a UI design into a component hierarchy and implement it with JSX, typed props and composition through children.
Prerequisites: JavaScript Foundations
01. The problem
The design for a shop-admin page has a toolbar: a prominent Checkout button, a quieter Empty cart button that is disabled while the cart is empty, and two status badges with different tones. These four pieces will appear all over the product, each time with different text, so they must become reusable components — and reusable means typed: whoever uses them next month gets editor completion and an error at compile time instead of a broken interface at run time.
This worked example starts from the way most first attempts look, reads what the compiler says, and fixes each problem properly: a typed Badge that wraps arbitrary content, and a Button that accepts every native button attribute without redefining them one by one. The examples were checked with TypeScript 7.0.2 with strict on (since TypeScript 6.0, strict is on by default, so a tsconfig.json without the flag reports the same errors); the TypeScript foundations skill covers the language itself.
02. Step 1: the untyped version, and what the compiler says
function Badge({ label, count }) {
return (
<span className="badge">
{label}: {count}
</span>
);
}
export function Demo() {
return <Badge label="Low stock" count={3} />;
}src/broken-props.tsx(1,18): error TS7031: Binding element 'label' implicitly has an
'any' type.
src/broken-props.tsx(1,25): error TS7031: Binding element 'count' implicitly has an
'any' type.Strict TypeScript refuses to guess: with no props type, label and count are any, so typos, missing props and wrong types would all reach the browser silently. The fix is a type for the props object. In this project it lives next to the component as a type alias, but an inline object type in the parameter list works the same way — you saw both spellings in the previous lesson.
03. Step 2: a typed Badge that wraps any content
import type { ComponentProps, ReactNode } from 'react';
import { renderToString } from 'react-dom/server';
type BadgeProps = {
tone: 'neutral' | 'success' | 'warning';
children: ReactNode;
};
function Badge({ tone, children }: BadgeProps) {
return <span className={`badge badge-${tone}`}>{children}</span>;
}Three decisions in eleven lines are worth naming. The tone is a union of literals, not string: only the three tones the design system defines are valid, and passing "gren" is a compile error rather than an invisible styling bug. The content type is ReactNode, the widest type React can render — text, numbers, other components, arrays of them, or nothing. That wideness is the point: a badge may hold a word or a whole element, and children is where React puts whatever appears between the component's tags. Finally, the class is built from the tone with a template literal, so the styling contract is one class name, not a free-form className prop the caller could spell wrong.
05. Step 4: compose the toolbar
function Toolbar() {
return (
<div role="toolbar" aria-label="Cart actions">
<Button variant="primary">Checkout</Button>
<Button variant="ghost" disabled>
Empty cart
</Button>
<Badge tone="success">In stock</Badge>
<Badge tone="warning">2 left</Badge>
</div>
);
}
console.log(renderToString(<Toolbar />).replaceAll('><', '>\n<'));Run the file directly with node --import tsx src/toolbar.tsx. tsx follows the project's tsconfig.json, which must set "jsx": "react-jsx" (for example { "compilerOptions": { "strict": true, "jsx": "react-jsx" } }) so JSX compiles to the automatic runtime; without it the run stops with ReferenceError: React is not defined.
<div role="toolbar" aria-label="Cart actions">
<button type="button" class="btn btn-primary">Checkout</button>
<button disabled="" type="button" class="btn btn-ghost">Empty cart</button>
<span class="badge badge-success">In stock</span>
<span class="badge badge-warning">2 left</span>
</div>Compare the four call sites with the output: every prop became the right attribute, and nothing had to be repeated. Checkout needed only a variant; the disabled button passed a plain HTML attribute straight through the spread without Button ever naming it. The disabled button kept its type="button" even though the caller never mentioned it, and no component in the file knows how the others are styled. Also notice what the caller of a component sees: role="toolbar" and its accessible name are part of the wrapper's markup, so keyboard and screen-reader users get a named toolbar for free — the same labelling discipline as in alternatives and labels.
06. Check your understanding
07. Apply it
From your shopping-list sketch, type two components end to end before you style them: a Chip (tone plus children) and a RemoveButton that forwards native button attributes and defaults type correctly. Write the props type first, then the component, then a call site that passes a prop spelled wrong on purpose — and read the compiler error. Repeat the exercise with one input element using ComponentProps<'input'>; note that aria-* attributes arrive through the same forwarding, which is how this project's own components/ui buttons stay accessible while remaining reusable.
08. Review prompt
Without looking back: write the props type for a tone-limited badge from memory, and explain in two sentences what ComponentProps<'button'> buys that a hand-written list of attributes does not. Then say, in order, what a component should do with a prop it owns, a prop it wants to default, and everything else.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.