2

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 3

1

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';
Sign up to request clarification or add additional context in comments.

4 Comments

TypeError: Cannot read property 'arrayOf' of undefined
updated my answer. you need also to import PropTypes
OK.. it works when I use PropTypes from 'prop-types' library but not from React: import PropTypes, { bool, string } from 'prop-types'
you could destructure all instead like import { bool, string, arrayOf, shape } from 'prop-types', and remove all PropTypes. it's up to your preference :)
1
MyComponent.propTypes = {
    myProps: PropTypes.arrayOf(
        PropTypes.shape({
            active: PropTypes.bool.isRequired,
            status: PropTypes.string
        })
    )
    .isRequired
}

1 Comment

TypeError: Cannot read property 'arrayOf' of undefined
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.