Tushar Kumawat
Tushar Kumawat

Reputation: 661

Cannot read property 'map' of undefined in react js

I am creating custom components of select and facing some issues. Showing this error Cannot read property 'map' of undefined. I want to map select option and use in pages from props

function CustomSelect(props) {
  const classes = useStyles();
  const options = [
    "Religion", 
    "Internal ", 
    "Not Profit", 
  ];
  const {
    age,
    setAge,
    list
  } = props;

  const handleChange = (event) => {
    setAge(event.target.value);
  };

  return (
    <FormControl variant="filled" className={classes.formControl}>
      <InputLabel id="demo-simple-select-filled-label">Age</InputLabel>
        <Select
          labelId="demo-simple-select-filled-label"
          id="demo-simple-select-filled"
          value={age}
          onChange={handleChange}
        >
        {list.map(item => (
            <MenuItem value="test">
                {item.options}
            </MenuItem>
          ))}
      </Select>
    </FormControl>
  )
}

Upvotes: 1

Views: 3027

Answers (1)

Drew Reese
Drew Reese

Reputation: 203476

list is passed as a prop, so in this situation you should probably provide a default value.

function CustomSelect(props) {
  const classes = useStyles();
  const options = [
    "Religion", 
    "Internal ", 
    "Not Profit", 
  ];
  const {
    age,
    setAge,
    list = [], // <-- provide an initial value if undefined
  } = props;

  const handleChange = (event) => {
    setAge(event.target.value);
  };

  return (
    <FormControl variant="filled" className={classes.formControl}>
      <InputLabel id="demo-simple-select-filled-label">Age</InputLabel>
        <Select
          labelId="demo-simple-select-filled-label"
          id="demo-simple-select-filled"
          value={age}
          onChange={handleChange}
        >
        {list.map(item => (
            <MenuItem value="test">
                {item.options}
            </MenuItem>
          ))}
      </Select>
    </FormControl>
  )
}

You should probably also define propTypes so you can ensure the correct type is passed.

Typechecking with PropTypes

import PropTypes from 'prop-types';

CustomSelect.propTypes = {
  list: PropTypes.array.isRequired,
};

If you can, be as specific as possible

list: PropTypes.arrayOf(PropTypes.shape({
  options: PropTypes.string.isRequired,
}))

The .isRequired bit will throw a warning in non-production builds that the list prop is undefined or otherwise not been passed.

Upvotes: 2

Related Questions