Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 978
John M. Avatar asked Oct 18 '25 23:10

John M.


1 Answers

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.

like image 79
CRice Avatar answered Oct 20 '25 12:10

CRice