gotohayato.com

React の PropTypes.element と PropTypes.elementType の違い

JavaScriptReact

JavaScript のフレームワーク React で使われる PropTypes.element と PropTypes.elementType の違いについてです。 両者には次の違いがあります。

意味例
PropTypes.elementReact エレメント<MyButton />
PropTypes.elementTypeReact エレメントタイプMyButton

関係としては element がインスタンスで elementType がクラスという捉え方でよいようです。

尚、確認に使用した React と PropTypes のバージョンは次のとおりです。

  • react: 16.14.0
  • prop-types: 15.7.2

以下サンプルです。

PropTypes.element

次の MyComponent は left と right というプロパティを受け取ります。 left と right はいずれも PropTypes.element です。

import React from "react"
import PropTypes from "prop-types"

const MyComponent = ({ left, right }) => {
  return (
    <div>
      <div>{left}</div>
      <div>{right}</div>
    </div>
  )
}

MyComponent.propTypes = {
    left: PropTypes.element.isRequired,
    right: PropTypes.element.isRequired,
}

const App = () => {
  return (
    <MyComponent
      left={<img src="left.png" />}
      right={<img src="right.png" />}
    />
  )
}

PropTypes.elementType

次の MyComponent は button というプロパティを受け取ります。 button は PropTypes.elementType です。

import React from "react"
import PropTypes from "prop-types"

const MyComponent = ({ btn }) => {
   return (
     <btn>送信</btn>
   )
}

MyComponent.propTypes = {
  button: PropTypes.elementType.isRequired,
}

const MyButton = ({ children }) => (
  <div><button>{children}</button></div>
)

const App = () => {
  return (
    <MyComponent btn={MyButton} />
  )
}

ちなみに、特定のコンポーネントのインスタンスに制限したい場合は PropTypes.instanceOf() が使えるようです。

MyComponent.propTypes = {
  button: PropTypes.instanceOf(MyButton),
}

参考