jollelj jollelj - 25 days ago 7
React JSX Question

React PropTypes - shape with numbers as keys

I'm trying to specify the PropTypes for one of my React components and have run into some problems. The object I'm trying to describe is going to look like this (the array will contain multiple objects):

rounds: {
1: [
{
date: 1429354800000,
arena: 'Arena name',
scoreHome: 3,
scoreAway: 2,
teamHome: 'Home team name',
teamAway: 'Away team name',
spectators: 10
}
]
}


I will not know in advance how many rounds there will be. So I could end up with

rounds: { 1: [..], 2: [..], 3: [..] }


This is what I currently have (not working):

RoundsTable.propTypes = {
rounds: PropTypes.shape({
PropTypes.arrayOf(PropTypes.shape({
date: PropTypes.number.isRequired,
arena: PropTypes.string.isRequired,
scoreHome: PropTypes.number.isRequired,
scoreAway: PropTypes.number.isRequired,
teamHome: PropTypes.string.isRequired,
teamAway: PropTypes.string.isRequired,
spectators: PropTypes.number.isRequired
}).isRequired).isRequired
}).isRequired
}


I'm not sure how to specify the number that contains the array of objects. Is it a data design problem on my side or is there a simple solution for specifying these kinds of props?

Answer

This is a data design problem. You are using an Object as an array. For example, this would work if you changed your data accordingly:

RoundsTable.propTypes = {
  rounds: PropTypes.arrayOf(PropTypes.shape({
      date: PropTypes.number.isRequired,
      arena: PropTypes.string.isRequired,
      scoreHome: PropTypes.number.isRequired,
      scoreAway: PropTypes.number.isRequired,
      teamHome: PropTypes.string.isRequired,
      teamAway: PropTypes.string.isRequired,
      spectators: PropTypes.number.isRequired
    }).isRequired).isRequired
}

The data would look like this:

rounds: [
       {
         date: 1429354800000,
         arena: 'Arena name',
         scoreHome: 3,
         scoreAway: 2,
         teamHome: 'Home team name',
         teamAway: 'Away team name',
         spectators: 10
       },
       {...}
]

You lose the indexes, but arrays already have those. If you wanted more map-like functionality, you would need to decide what kind of map to use and base your PropTypes on that. Javascript does not have native maps, though people very often use Object for the same purpose, that has a number of limitations, such as the one you have run into.