Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

× TypeError: Cannot read properties of undefined (reading 'map')

When I try to run this code it gives me this error:

× TypeError: Cannot read properties of undefined (reading 'map')

I don't know why. I have tried possible means, but it didn't work.

import React from 'react';
import Grid from '@material-ui/core/Grid';

import Product from './Product/Product';
import useStyles from './styles';

const products = [
  {id: 1, name: 'Shoes', description: 'Running Shoes.' },
  {id: 2, name: 'MacBook', description: 'Apple MacBook.' },
];

const Products = ({ products }) => {
  const classes = useStyles();

  return (
    <main className={classes.content}>
      <div className={classes.toolbar} />
      <Grid container justify="center" spacing={4}>
        {products.map((products) => (
          <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
            <Product />
          </Grid>
        ))};
      </Grid>
    </main>
  );
};

export default Products;
like image 647
udenyi Avatar asked Sep 06 '21 21:09

udenyi


People also ask

How do you fix TypeError Cannot read properties of undefined reading map ')?

How to Fix the Error? In order to fix the error, you need to make sure that the array is not undefined . In order to do this, the simplest way is to use optional chaining. You can use optional chaining by introducing a question mark after the variable.


1 Answers

I had the same error and solved it by first asking if the array existed.

Example:

<Filter>
  { product.color?.map((c) => (
    <FilterColor color = {c} key = {c} />
  ))};
</Filter>
like image 115
jake Avatar answered Sep 20 '22 12:09

jake