John M.
John M.

Reputation: 875

What is the correct PropTypes for dictionary in reactjs

Have something like

x = {"k0": [v0, v1], "k1":[v2]}

How should I write the correct proptypes for x?

Upvotes: 4

Views: 5864

Answers (2)

CRice
CRice

Reputation: 32166

You could use PropTypes.shape to specify an object that contains both k0 and k1 keys, and use PropTypes.arrayOf to make sure they are arrays of whatever type v0, v1, and v2 are.

Some something like:

YourComponent.propTypes = {

  x: PropTypes.shape({
    k0: PropTypes.arrayOf(/* your type here, eg: PropTypes.number */),
    k1: PropTypes.arrayOf(/* other type here, eg: PropTypes.string */)
  })

}

Or, if you don't know the number or names of the keys beforehand, but they all have the same type, you can use PropTypes.objectOf. So to describe an object where every key maps to an array of strings:

x: PropTypes.objectOf(PropTypes.arrayOf(PropTypes.string))

You can read more about the available PropTypes here.

Upvotes: 8

mrshl
mrshl

Reputation: 531

Dictionaries in Javascript are also known as Objects.

x: PropTypes.object

Upvotes: 0

Related Questions