Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

reactjs - 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

question from:https://stackoverflow.com/questions/65852156/how-to-validate-props-as-an-array-of-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...