how to validate props as an array of objects?

Viewed 148

Here is part of a component where I pass props as an array of objects:

const data = [
    {
        active: true,
        status: 'Active'
    },
    {
        active: false,
        status: 'Done'
    }
]

<MyComponent myProps={data} /> 

Here is my component where I'm trying to validate props

import React from 'react'
import { bool, string } from 'prop-types'

const MyComponent = ({ myProps }) => {
    return (
        <div>
            <h1>Hello</h1>
        </div>
    )
}

MyComponent.propTypes = {
    active: bool.isRequired,
    status: string
}

export default MyComponent

The error I'm getting is:

The prop active is marked as required in MyComponent, but its value is undefined

3 Answers

you are passing down as props myProps.active and status are part of your object shape. With that in mind your propType should look like:

MyComponent.propTypes = {
  myProps: PropTypes.arrayOf(
    PropTypes.shape({
      active: PropTypes.bool.isRequired,
      status: PropTypes.string
    })
  )
}

also remember to import PropTypes at the top:

import PropTypes from 'prop-types';
MyComponent.propTypes = {
    myProps: PropTypes.arrayOf(
        PropTypes.shape({
            active: PropTypes.bool.isRequired,
            status: PropTypes.string
        })
    )
    .isRequired
}

I think you need two components, a HOC (High Order Component) that receives your array, with an prop:

MyComponentHoc.propTypes = {
    data: PropTypes.array.isRequired,
};

And then Call to your visual component inside:

const MyComponentHoc = (data) => data.map(MyComponent);
Related