Props & children; event handlers; refs
Define typed props and children; wire up event handlers safely; create and use refs to access DOM nodes.
Intro
Goal: Build typed React components: define props (with children), attach event handlers with precise types, and focus an input using refs.
- Typed props interfaces
- Event handler types
- Refs for DOM access
Typed props
Declare a props interface; use optional props and narrow with union literals. Keep defaults inside the component.
import React from "react"
interface BadgeProps {
text: string
color?: "primary" | "success" | "warning"
}
export function Badge({ text, color = "primary" }: BadgeProps) {
const bg = color === "success" ? "#16a34a" : color === "warning" ? "#d97706" : "#2563eb"
return <span style={{ backgroundColor: bg, color: "white", padding: 4, borderRadius: 6 }}>{text}</span>
}
export default function App() {
return (
<div style={{ display: "grid", gap: 8 }}>
<Badge text="Saved" color="success" />
<Badge text="Warn" color="warning" />
</div>
)
}All lessons in this course
- Props & children; event handlers; refs
- State & reducers; Context typing
- Component generics — intro