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

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.