Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React PropType check dynamic object

I have an empty object initially.

const foo = {};

It will be going to change to,

const foo = {
 a: 'data',
 b: 'data',
 .
 .
 nth
};

How to define PropTypes for this or do I need to make custom type checker for this ?

like image 551
Bimal Grg Avatar asked Feb 04 '23 00:02

Bimal Grg


2 Answers

You can use like this:

All values of object should have instance of String:

foo: PropTypes.objectOf(PropTypes.string),

For further interest:

Any values of object can be passed:

foo: PropTypes.objectOf(PropTypes.any),

Object can only have a and b as its property:

foo: PropTypes.shape({
    a: PropTypes.string,
    b: PropTypes.number
}),

Or, custom validation:

foo: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  },
like image 188
Bhojendra Rauniyar Avatar answered Feb 06 '23 13:02

Bhojendra Rauniyar


To define your shape with PropTypes you would use something like:

import PropTypes from 'prop-types';

// your component
const Component = () => <p>Hello world</p>

Component.propTypes = {
  foo: PropTypes.shape({
    a: PropTypes.string,
    b: PropTypes.string,
  }),
}

Apart from that I'm not sure what you mean :)

like image 30
Dominik Avatar answered Feb 06 '23 12:02

Dominik