error map in missing props reactjs proptypes

Viewed 6977

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

You can't have propTypes on the props object because every react component stateless/stateful is decorated with the props object. Also you can't check on !props because even if you don't have any prop in your component your props will be empty object {}

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

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

ListComponent.propTypes = {
    names: PropTypes.arrayOf(PropTypes.string)
};

export default ListComponent

Here you can define your component using <ListComponent names= {['name1', 'name2' ]} />

if you want to iterate the props you can use lodash library check my example

import React, { Fragment } from "react";
import PropTypes from "prop-types";
import _ from "lodash";

const ListComponent = props => {
  return (
    <Fragment>
      {_.map(props,( item,key) => {           
        return <div key={key}>{key}: {item}</div>
      })}
    </Fragment>
  );
};

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

export default ListComponent;

Using

<ListComponent  name="david" lastName:"zls"/>
//render
name: david
lastname: zls
Related