Hope someone can help me out.
I am trying to dynamically create some cards on my webpage out of a dictionary.
I tried to create the function but the code inside the first <div>
cards.map((character)=>(
is not recognizing the array of dictionaries.
Any ideas on how to fix it?
function MemoryCards() {
const images = [
"./img/Abadango.jpeg",
"./img/abradolf.jpeg",
"./img/Adjudicator.jpeg",
"./img/AgencyDirector.jpeg",
"./img/Alan.jpeg",
"./img/Albert.jpeg",
"./img/Alexander.jpeg",
"./img/AlienMorty.jpeg",
"./img/AlienRick.jpeg",
"./img/Annie.jpeg",
"./img/AntsJonson.jpeg",
"./img/Beth.jpeg",
"./img/Jerry.jpeg",
"./img/morty.jpeg",
"./img/ricky.jpeg",
"./img/summer.jpeg"
]
const cards = [];
let len = images.length;
for (let i = 0; i < len; i ) {
let end = images[i].indexOf('.', 3);
let name = images[i].substring(6, end);
let card = { 'name': name, 'img': images[i], 'id': i };
cards.push(card);
}
return (
<div>
cards.map((character)=>(
<div >
<div className="card_header">
<img src={cards.img}></img>
</div>
<div className="card_body">
<h3>{cards.name}</h3>
</div>
</div>
))
</div>
)
}
export default MemoryCards;
CodePudding user response:
Inside your loop you have {cards.img}
and {cards.name}
but what you want is {character.img}
and {character.name}
Also you are missing curly brackets {}
before initializing cards
loop
Note, you have a typo, instead of className
you have just class
here: <div >
function MemoryCards() {
const images = [
"./img/Abadango.jpeg",
"./img/abradolf.jpeg",
"./img/Adjudicator.jpeg",
"./img/AgencyDirector.jpeg",
"./img/Alan.jpeg",
"./img/Albert.jpeg",
"./img/Alexander.jpeg",
"./img/AlienMorty.jpeg",
"./img/AlienRick.jpeg",
"./img/Annie.jpeg",
"./img/AntsJonson.jpeg",
"./img/Beth.jpeg",
"./img/Jerry.jpeg",
"./img/morty.jpeg",
"./img/ricky.jpeg",
"./img/summer.jpeg"
];
const cards = [];
let len = images.length;
for (let i = 0; i < len; i ) {
let end = images[i].indexOf(".", 3);
let name = images[i].substring(6, end);
let card = { name: name, img: images[i], id: i };
cards.push(card);
}
return (
<div>
{cards.map((character, idx) => (
<div key={idx} className="card">
<div className="card_header">
<img src={character.img} alt="" />
</div>
<div className="card_body">
<h3>{character.name}</h3>
</div>
</div>
))}
</div>
);
}
export default MemoryCards;
CodePudding user response:
You need to wrap your variables in curly braces {}
for it to work inside JSX:
return (
<div>
{cards.map((card)=>(
<div key={card.name} >
<div className="card_header">
<img src={card.img}></img>
</div>
<div className="card_body">
<h3>{card.name}</h3>
</div>
</div>
))}
</div>
)
In the example above, you can see that the entire map block should be inside the curly braces, also don't forget to add an ID to the element inside the map and to use the actual variable defined inside the map function