Search code examples
reactjsreact-props

how to validate props as an array of objects?


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


Solution

  • 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';