Default property value in React component using TypeScript

When working with React components in TypeScript, you may often find yourself needing to set default values for certain properties. In this blog post, we will explore different ways to set default property values in React components using TypeScript.

1. Using defaultProps

The easiest way to set default property values in React components is by using the defaultProps property. This approach works for both JavaScript and TypeScript.

Here’s an example:

{`import React from 'react';

interface MyComponentProps {
  name: string;
  age: number;
}

const MyComponent: React.FC = ({ name, age }) => {
  // Component logic here
};

MyComponent.defaultProps = {
  name: 'John Doe',
  age: 30,
};

export default MyComponent;`}

2. Using a default value in the component

If you prefer to set default values directly in the component, you can do so by using the logical OR operator (||) to provide a default value if the property is undefined.

Here’s an example:

{`import React from 'react';

interface MyComponentProps {
  name?: string;
  age?: number;
}

const MyComponent: React.FC = ({ name = 'John Doe', age = 30 }) => {
  // Component logic here
};

export default MyComponent;`}

3. Using a function to set default values

If you need more complex default values or want to calculate them dynamically, you can use a function to set the default values.

Here’s an example:

{`import React from 'react';

interface MyComponentProps {
  name: string;
  age: number;
}

const getDefaultName = (): string => {
  // Calculate default name here
  return 'John Doe';
};

const getDefaultAge = (): number => {
  // Calculate default age here
  return 30;
};

const MyComponent: React.FC = ({ name = getDefaultName(), age = getDefaultAge() }) => {
  // Component logic here
};

export default MyComponent;`}

These are three different ways to set default property values in React components using TypeScript. Choose the one that best fits your needs and coding style.

Happy coding!


Posted

in

,

by

Tags:

Comments

Leave a Reply

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