thacoon's Blog

Default Props in React and Typescript

· thacoon

Lately I started to do some frontend related stuff and started working with React. At the start when using JS I was using PropTypes for typechecking. When using Proptypes it is easy to create optional properties you just need to add them to defaultProps. Later I switched to typescript to get better type checks in the whole codebase and a better developer experience. But when I came to the point where I needed to have an property with some default I could not find any easy to understand solution. But today I found a easy solution on this GitHub issue, for Typescript 3.1 or above. The following example shows you how to make a default property in React with Typescript.

 1import React from 'react';
 2
 3interface Props {
 4  greeting?: string
 5  planet: string
 6}
 7
 8const Greet = (props: Props) => {
 9  const { greeting, planet } = props;
10
11  return (
12    <p>
13      {`${greeting} from ${planet}`}
14    </p>
15  );
16};
17
18Greet.defaultProps = {
19  greeting: 'Hello',
20} as Partial<Props>;
21
22const component = <Greet planet="Earth" />

The as Partial<Props> is not necessary but it is a good practice as without it you could use wrong type as a default prop and TypeScript wouldn’t complain.

References

Resources

#frontend #react #typescript

Reply to this post by email ↪