"TypeError: Cannot read property 'name' of undefined" when looping on JSON "TypeError: Cannot read property 'name' of undefined" when looping on JSON json json

"TypeError: Cannot read property 'name' of undefined" when looping on JSON


Assuming your code is wrapped in a function component (see below), it may be an issue with how you're importing / using cards.json. Also in the useEffect, make the dependency array [] instead of [cards]. I changed your code to this and it works:

import React, { useEffect, useState } from "react";import cardsJson from "./cards.json";export function Cards() {  const [cards, setCards] = useState();  useEffect(() => {    console.log(cardsJson);    setCards(cardsJson.cards);  }, []);  return (    <div>      {        cards &&        cards.map((card, index) => (          <div key={card.name} className="cardHero">            <div className="front">{card.name}</div>            <div              className="back"            ></div>          </div>        ))      }    </div>  );}

Note I put the cards.json in the same folder as the Cards component, I'm not outputting the image and I updated the dependency array.


If you only want to display the cards there is no reason for them to be inside a useEffect. I recommend you to create a constant and initialize it with cardsJson.cards, like:

const cards = cardsJson.cards;

Or if you want to play with states, just initialize your state with cardsJson.cards, like:

const [cards, setCards] = useState(cardsJson.cards);