How to do nested arrayOf proptype validation in React

1.8k views Asked by At

I'm currently going through an eslint upgrade of our existing React codebase. As part of the updated Eslint rules, we need to start being more specific about our PropTypes. (Don't use PropTypes.object, PropTypess.array)

I can't refactor very much, as it's out of the scope of what I'm doing right now.

Currently there's an array of arrays being passed as a prop to a component which generates a table.

Data looks like:

[ [ 'firstName', 'lastName', 35, 'M', 1, '' ],
  [ 'firstName', 'lastName', 34, 'F', 1, '' ] ]

Ideally I would change this to an array of objects where I can validate each key:value individually, but this piece of data is very involved, so I can't change it.

Here's what I want to do:

tableData: PropTypes.arrayOf(
  PropTypes.arrayOf(
    PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ])
  )
)

However, react keeps giving me this error:

Warning: Failed prop type: Invalid prop 'tableData[0][2]' supplied to 'MyComponent'

I've tried doing something like this too:

tableData: PropTypes.arrayOf(
  PropTypes.arrayOf(
    PropTypes.string,
    PropTypes.string,
    PropTypes.number,
    PropTypes.string,
    PropTypes.number,
    PropTypes.string
  ) 
)

But that also didn't work.

Do I need to create my own PropType validator? I'd really like to avoid that, especially because I feel like my methods should be working.

0

There are 0 answers