V
V
valerav2018-06-18 15:14:46
React
valerav, 2018-06-18 15:14:46

How to validate a props object with a dynamic key?

In props comes an object of the form:

{
    'Динамический_ключ_1': {
        id: 1,
        title: 'title 1',
        text: 'text 1'
    },
    'Динамический_ключ_2': {
        id: 2,
        title: 'title 2',
        text: 'text 2'
    }
}

The dock has a function PropTypes.objectOf, which can take a function as the first argument, inside which you can get all the values ​​of the object being checked, in this case (title, text, id). Question: How do I check these values ​​using the "prop-types" library? Or you need to do something like:
const id = 25;
if (typeof id !== 'string') throw new Error(`${id} не строка`);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anatoly Zharov, 2018-06-18
@valerav

There are lines in the documentation about this:

// An object with property values of a certain type
  optionalObjectOf: PropTypes.objectOf(PropTypes.number),

  // An object taking on a particular shape
  optionalObjectWithShape: PropTypes.shape({
    color: PropTypes.string,
    fontSize: PropTypes.number
  }),

in your case it will be something like
PropTypes.objectOf(PropTypes.shape({
    id: PropTypes.number,
    title: PropTypes.string,
    text: PropTypes.string,
}))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question