Set optional props with default values in React TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 29, 2024
2 min

banner

# 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> ); }

set optional props with default values in react typescript

The code for this article is available on GitHub

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.

I've also written a detailed guide on how to use create-react-app with TypeScript.

# Setting an entire props object as optional

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> ); }
The code for this article is available on GitHub

All of the properties in the EmployeeProps type are marked as optional, so the component can be used without being provided 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev