How to specify (optional) default props with TypeScript for stateless, functional React components?

When working with React components, it is common to have stateless, functional components that do not have their own state. These components receive props from their parent components and render based on those props. In TypeScript, we can specify default props for these stateless components using a combination of defaultProps and the Partial utility type.

Let’s say we have a stateless component called MyComponent that receives a prop called name. We want to specify a default value for name in case it is not provided by the parent component. Here’s how we can achieve that:

import React from 'react';

type Props = {
  name: string;
};

const MyComponent: React.FC> = ({ name }) => {
  return 
Hello, {name}!
; }; MyComponent.defaultProps = { name: 'Guest', }; export default MyComponent;

In the code snippet above, we define the Props type which represents the expected props for MyComponent. We then define MyComponent as a React functional component using the React.FC type. We use the Partial utility type to make all props optional, allowing us to specify default values for them.

Finally, we set the defaultProps property on MyComponent to specify the default value for name. In this case, we set it to ‘Guest’.

Now, if a parent component does not provide a value for name, MyComponent will render ‘Hello, Guest!’ as the default value.

Alternatively, if you prefer not to use the Partial utility type, you can manually make props optional by adding a question mark after their names in the Props type definition. Here’s an example:

import React from 'react';

type Props = {
  name?: string;
};

const MyComponent: React.FC = ({ name = 'Guest' }) => {
  return 
Hello, {name}!
; }; export default MyComponent;

In this case, we define the name prop as optional by adding a question mark after its name in the Props type definition. We also set the default value directly in the function parameter using the assignment operator.

Both approaches achieve the same result, allowing you to specify default props for stateless, functional React components in TypeScript. Choose the one that fits your coding style and preferences.


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *