Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error map in missing props reactjs proptypes

I'm using Proptypes and I'm getting

error 'map' is missing in props validation react/prop-types

How should I validate this map?

import React, { Fragment } from 'react'
import PropTypes from 'prop-types';

const ListComponent = props => {
    if (!props) return null
    return (
        <Fragment>
            {props.map((item,i) => <div key={i}>{item.name}</div>)}
        </Fragment>
    )
}

ListComponent.propTypes = {
    props: PropTypes.any
};

export default ListComponent
like image 259
NoHoney_k1ll Avatar asked Dec 13 '22 13:12

NoHoney_k1ll


1 Answers

When you have a stateless component as yours, the props argument contains the props, it's a plain object.

You are trying to iterate over it, and it's not possible because it's an object and not an array.

To add a proper prop-type check, you need to know (and tell us) the prop to check inside props.

Let's say that your ListComponent has an items prop with inside a prop name, then you should something like this:

import React, { Fragment } from 'react'
import PropTypes from 'prop-types';

const ListComponent = ({ items }) => {
    if (!items) return null
    return (
        <Fragment>
            { items.map((item, i) => <div key={i}>{item.name}</div>)}
        </Fragment>
    )
}

ListComponent.propTypes = {
    items: PropTypes.arrayOf(
      PropTypes.shape({
        name: PropTypes.string
      })
    )
};

export default ListComponent
like image 90
0xc14m1z Avatar answered Jan 02 '23 13:01

0xc14m1z