I am new to React and dev in general, but I am struggling to figure out how to achieve what I am trying to do. I feel as though I may have missed something along the way.
My goal is to have a list of items, that which on clicked individually, will toggle the visibility of their information.
The problem is that I am not able to map over the state in the parent element to display each object. But the state is in an array so I don't understand why it wouldn't be iterable. I do not get this problem when its just an object that I pass props to the child without state.
Is this the correct way to go about doing this? Am I supposed to create another array just to map over my object? I've also been a little confused as some sources create a class and use the constructor and render function. Is that deprecated or should I be doing it this way?
Parent
import React from "react";
import { useState } from "react";
//Components
import Card from "./Card";
const CardStack = () => {
const [habits, setHabits] = [
{
id: 1,
merit: "good",
title: "Good Habit",
count: 4,
text: "Words to be hidden",
visible: false,
},
{
id: 2,
merit: "bad",
title: "Bad Habit",
count: 1,
text: "Words to be hidden",
visible: false,
},
{
id: 3,
merit: "good",
title: "Good Habit",
count: 6,
text: "Words to be hidden",
visible: true,
},
];
const toggleCard = () => {
this.setHabits((habit) => {
habit.visible = !visible;
});
};
return (
<div className="card-stack">
{habits.map((habit) => (
<Card habit={habit} key={habit.id} onClick={toggleCard} />
))}
</div>
);
};
export default CardStack;
Child
import React from "react";
//Components
import Button from "./Button";
const Cards = ({ habit, onClick }) => {
return (
<div className="card" key={habit.id} onClick={onClick}>
<h4 className="title" merit={habit.merit}>
{habit.title}
<div className="btn-group">
<Button className="button" />
<span className="count">{habit.count}</span>
<Button className="button" />
</div>
{habit.visible ? (
<div className="content">
<p>visible</p>
</div>
) : null}
</h4>
</div>
);
};
export default Cards;
const [habits, setHabits] = useState([....])toggleCardmethod will overwritehabits, which starts as an array, with the boolean returned fromhabit.visible = !visible;. (And you don't calluseStateas noted by @talfreds). Also,thisis not needed, and probably not pointing to the right 'this' anyway since you're using it in an arrow function.