13
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【React】【typescript】Functional Component の defaultProps の定義方法

Last updated at Posted at 2019-04-08

はじめに

最近 React Component を実装する際は Functional Component で書いています。
その際、 defaultProps の解決方法に躓いたので書きます。

他でよく紹介されている方法

import React from 'react';

type Props = {
  foo?: string;
}

const BarComponent = (props: Props) => {
  return (
    <div>{props.foo}</div>
  );
}
BarComponent.defaultProps = {
  foo: 'FOO'
}

この方法だと props.foostring | undefined になってしまうという問題があります。

解決方法

import React from 'react';

type Props = {
  foo?: string;
}

const BarComponent = ({ foo = 'FOO' }: Props) => {
  return (
    <div>{foo}</div>
  );
}

これで foostring になります。

というのを上司に教えてもらいました。
これで問題があれば教えてください。

13
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?