Home > Software engineering >  I getting this error 'Uncaught Error: Objects are not valid as a React child' even if I us
I getting this error 'Uncaught Error: Objects are not valid as a React child' even if I us

Time:12-19

`

const fashionCardData = [
  { id: "1", src: "1.png" },
  { id: "2", src: "2.png" },
  { id: "4", src: "4.png" },
];

const Products = () => {
  return (
    <Box>
      {fashionCardData.map((item)=>{
        <img key={item.id} src={`images/${item.src}`} alt={item.id}/>
      })}
    </Box>
  );
};

`

I am trying to map an array but it doesn't work please help

CodePudding user response:

Replace

{fashionCardData.map((item)=>{
    <img key={item.id} src={`images/${item.src}`} alt={item.id}/>
  })}

with

{fashionCardData.map((item)=>(
    <img key={item.id} src={`images/${item.src}`} alt={item.id}/>
  ))}

CodePudding user response:

In your code, you are trying to map over the fashionCardData array and render an img element for each item, but you are missing the return statement in the map callback function. To fix the error, you need to add a return statement to the map callback function like this:

const Products = () => {
  return (
    <Box>
      {fashionCardData.map((item)=>{
        return <img key={item.id} src={`images/${item.src}`} alt={item.id}/>
      })}
    </Box>
  );
};

Alternatively, you can use an arrow function to concisely return the element like this:

const Products = () => {
  return (
    <Box>
      {fashionCardData.map((item)=> (
        <img key={item.id} src={`images/${item.src}`} alt={item.id}/>
      ))}
    </Box>
  );
};

I hope this helps! Let me know if you have any questions or if you need further assistance.

CodePudding user response:

Problem is you are not returning the component.

Change your code to

{fashionCardData.map((item)=>{
    return (<img key={item.id} src={`images/${item.src}`} alt={item.id}/>);
  })}

Code that is inside {} will be treated as javascript and similarly code that is inside () will be treated as jsx.

  • Related