EN
React - different types of PropType for one prop
0 points
In this article, we would like to show you how to allow different types of PropType for one prop in React.
The first thing we need to do is install the prop-types package using the following command:
xxxxxxxxxx
1
npm install --save prop-types
Then import to our project using:
xxxxxxxxxx
1
import PropTypes from 'prop-types'; // ES6
2
var PropTypes = require('prop-types'); // ES5 with npm;
Then, add your propTypes
after defining the functional component, before exporting. Use array notation with oneOfType
to declare the types of props you want.
Practical example:
xxxxxxxxxx
1
import React from 'react';
2
import PropTypes from 'prop-types';
3
4
const MyComponent = ({ color }) => (
5
<div>The color or it's hex code is: {color}</div>
6
);
7
8
MyComponent.propTypes = {
9
color: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
10
};
11
12
const App = () => {
13
return (
14
<div>
15
<MyComponent color='red' />
16
</div>
17
);
18
};
19
20
export default App;
Note:
A better solution is to start programming in TypeScript.