Languages
[Edit]
EN

React - different types of PropType for one prop

0 points
Created by:
Savannah
319

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:

npm install --save prop-types

Then import to our project using:

import PropTypes from 'prop-types'; // ES6
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:

import React from 'react';
import PropTypes from 'prop-types';

const MyComponent = ({ color }) => (
  <div>The color or it's hex code is: {color}</div>
);

MyComponent.propTypes = {
  color: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};

const App = () => {
  return (
    <div>
      <MyComponent color='red' />
    </div>
  );
};

export default App;

Note:

A better solution is to start programming in TypeScript.

References

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join