LoginSignup
2
0

More than 5 years have passed since last update.

PropTypesでpropsのデータ型を指定する

Posted at

はじめに

Reactでは、型チェックによるミスが思いもよらないバグの温床になることがあります。
それをprops-typesライブラリを使うことで防ぐことができます。

Greeting.js
import React from 'react';
import PropTypes from 'prop-types';

function Greeting(props) {
  return(
    <div>Hi {props.name}</div>
  );
}

Greeting.propTypes = {
  name: PropTypes.string
};

export default Greeting;

1. PropTypesをインポートする

import PropTypes from 'prop-types';

2. コンポーネントに対してpropTypesを使う

コンポーネント.propTypes = {
  props名: PropTypes.データ型
};
Greeting.propTypes = {
  name: PropTypes.string
};

ここでは、nameに文字列を指定している。

参考

公式ドキュメント

2
0
0

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
2
0