traintocode

Optional Props

In React, props can be required or optional. TypeScript helps ensure that required props are always passed to your component, and optional props are never assumed to exist in your component logic.

Hover your mouse over <MyChildComponent /> on the right and read the error:

Property 'name' is missing in type '{}' but required in type 'Props'.

This error is TypeScript telling you that the name prop is required by <MyChildComponent />.

You can make props optional by adding ? after the property name.

type Props = {
    myProps?: string
}
Exercise
1. Make the name prop optional, then read the error that appears on line 10.

2. Fix the error by conditionally rendering the enitre <p> tag only if name was supplied in the props.

Ask me about the errors you see, or anything else you need help with:

    You cannot do the coding exercises on this device, visit this page on a larger screen.
    App.tsx
    Loading...