Can you set multiple data types for an expected prop?

Question

In this lesson, we learned how to set a data type for each excepted prop of a component. Can you set multiple data types for an expected prop?

Answer

Yes, you can allow an expected prop to have multiple data types. To do this, you can utilize PropTypes.oneOfType(), which will let you list each type that can be expected.

import PropTypes from 'prop-types';

// In the following component, propOne can be
// of type string or boolean.
ExampleComponent.propTypes = {
  propOne: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.boolean
  ])
}
7 Likes

I think this line:

PropTypes.boolean

Needs to be:

PropTypes.bool
24 Likes

Do we need to import PropTypes from ‘prop-types’ when using .oneOfType() method??

1 Like

Can I make custom data type made through the default javascript class as one of the propType? if so, how would I do that?

sure, oneOfType is a method inside PropTypes object, so you need to import PropTypes first.

2 Likes