Handle default and optional props
Use defaults when an input is missing
A default parameter supplies a fallback for an omitted or undefined prop. This is JavaScript destructuring, not a special React operation. Choose a default only if it represents a meaningful behavior when the parent does not supply a value.
function StockLabel({ count = 5 }) { const text = count === null ? 'Unknown' : String(count); return <p>Stock: {text}</p>;}
export default function App() { return ( <main> <StockLabel /> <StockLabel count={undefined} /> <StockLabel count={0} /> <StockLabel count={null} /> </main> );}Expected lines: Stock: 5, Stock: 5, Stock: 0, Stock: Unknown. The default does not replace null or zero. The explicit null check communicates that the quantity is unknown rather than inventing a quantity. A common error is count || 5, which incorrectly replaces a valid zero. If both null and undefined should have a fallback, use the nullish coalescing operator, count ?? 5, only when that matches the contract.
Forward only the inputs a component accepts
function Label({ text, emphasis = false }) { return <p className={emphasis ? 'important' : 'normal'}>{text}</p>;}
export default function App() { const standard = { text: 'Ready to ship', emphasis: false }; return ( <main> <Label {...standard} /> <Label {...standard} emphasis={true} text="Packed" /> </main> );}Expected: two paragraphs, Ready to ship with class normal and Packed with class important. Styling is not supplied in this example. Later attributes override earlier spread properties of the same name. The spread is reasonable because the source object contains only known Label inputs. Label deliberately passes className and text to its paragraph, rather than forwarding arbitrary component-specific props to the DOM. Unreviewed spreading can leak irrelevant attributes or override intended values.
Document an explicit prop interface
interface PriceTagProps { readonly name: string; readonly price: number; readonly unit?: string;}
function PriceTag({ name, price, unit = 'credits' }: PriceTagProps) { return <p>{name}: {price} {unit}</p>;}
export default function App() { return <main><PriceTag name="Pen" price={3} /></main>;}Expected: Pen: 3 credits. This is a separate TSX example, not a replacement for the JSX file without changing the entry module. The interface describes the required name and price, and optional unit. The readonly modifiers discourage assignment through that typed object; they do not freeze values or guarantee runtime validation. TypeScript learners need the relevant React type definitions and TS configuration. Only TSX transformation has been checked here, not semantic React type checking. The JavaScript examples remain the main path.
Practice
Design a delivery label with a default of 3 days when days is missing or undefined, but display Same day for zero and Not scheduled for null. Specify the prop contract and predict four cases.