Set optional props with default values in React TypeScript

avatar

Borislav Hadzhiev

Tue May 03 20222 min read

banner

Photo by Alin Rusu

Set optional props with default values in React TypeScript #

To set optional props with default values in React TypeScript:

  1. Mark the props on the type as optional using a question mark.
  2. Provide default values for the props when destructuring them in the function's definition.
App.tsx
interface EmployeeProps { name?: string; // 👈️ marked optional age?: number; // 👈️ marked optional country: string; // 👈️ required (no question mark) } function Employee({name = 'Alice', age = 30, country}: EmployeeProps) { return ( <div> <h2>{name}</h2> <h2>{age}</h2> <h2>{country}</h2> </div> ); } export default function App() { return ( <div> <Employee name="Bob" age={29} country="Belgium" /> <hr /> <Employee country="Austria" /> </div> ); }

We marked the name and age props as optional.

This means that the component can be used with or without providing the name and age props.

If a value for an optional prop is not specified, it gets set to undefined.

Not providing a value for the prop and setting the prop to a value of undefined is the same.

We also set default values for the name and age parameters in the definition of the Employee component.

App.tsx
function Employee({name = 'Alice', age = 30, country}: EmployeeProps) { return ( <div> <h2>{name}</h2> <h2>{age}</h2> <h2>{country}</h2> </div> ); }

The name property in the object is set to Alice by default, so if the name prop is not provided, it would get assigned a value of Alice.

You could also set the entire props object as optional by marking all of its properties as optional.

App.tsx
interface EmployeeProps { name?: string; // 👈️ all marked optional age?: number; country?: string; } function Employee({ name = 'Alice', age = 30, country = 'Austria', }: EmployeeProps) { return ( <div> <h2>{name}</h2> <h2>{age}</h2> <h2>{country}</h2> </div> ); } export default function App() { return ( <div> <Employee name="Bob" age={29} country="Belgium" /> <hr /> <Employee /> </div> ); }

All of the properties in the EmployeeProps type are marked as optional, so the component can be used without being provided any props.

We set default values for all of the props of the Employee component, so if any of the props are omitted, the default values are used.

Use the search field on my Home Page to filter through my more than 1,000 articles.