user11284257
user11284257

Reputation:

How to declare proptypes to validate an array of specific strings?

A value passed to component can be an array of strings. That strings means different directions: top, right, bottom, left.

How to specify proptypes for component to allow only array of specified directions?

  <Arrows
    directions=['left', 'bottom'] // accepts the array
  />
  <Arrows
   directions=['left', 'back'] // doesn't accept the array
  />

Upvotes: 8

Views: 6149

Answers (2)

Isaac Oluwatemilorun
Isaac Oluwatemilorun

Reputation: 576

You can make use of PropTypes for the Runtime type checking for React props.

Using the PropTypes.arrayOf() option to ensure that an array of specific values are passed. And as an argument, you pass PropTypes.oneOf() which accepts an array of values (the directions of the Arrow) to select from.

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

class Arrow extends React.Component {
  render() {
    // ... do things with the props
  }
}

Arrow.propTypes = {
   directions: PropTypes.arrayOf(PropTypes.oneOf(['left', 'bottom']))
}

Upvotes: 5

Andrzej T
Andrzej T

Reputation: 440

Something like this should do the job:

directions: PropTypes.arrayOf(PropTypes.oneOf(['top', 'right', 'bottom', 'left'])),

Upvotes: 19

Related Questions