Categories
TypeScript Answers

How to set default property value in React component using TypeScript?

Spread the love

Sometimes, we want to set default property value in React component using TypeScript.

In this article, we’ll look at how to set default property value in React component using TypeScript.

How to set default property value in React component using TypeScript?

To set default property value in React component using TypeScript, we can put a type argument in the FunctionComponent type.

For instance, we write

interface PageProps {
  foo?: string;
  bar: number;
}

const PageComponent: FunctionComponent<PageProps> = (props) => {
  return (
    <span>
      Hello, {props.foo}, {props.bar}
    </span>
  );
};

PageComponent.defaultProps = {
  foo: "default",
};

to set the PageComponent component to the FunctionComponent<PageProps> type.

PageProps is an interface that has the optional foo property and the bar property.

And we set PageComponent.defaultProps to an object with the default value of foo set to 'default' which we need to do since we made foo optional in the PageProps interface.

Conclusion

To set default property value in React component using TypeScript, we can put a type argument in the FunctionComponent type.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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