'Map State in reactjs
I'm trying to map also functions from object
const KindOfShoots = [
{ id: 1, name: "Shoot in Studio",
link: "/Photoshoot",icon:"fa fa-calendar",
onClickAction: "setToggle1" },
{ id: 2, name: "Shoot at other Location",
link: "/Photoshoot" ,icon:"fa fa-calendar",
onClickAction: "setToggle2" },];
snippets below:
{
KindOfShoots.map((type)=>(
<KindOfShootLayout >
<div className="KindOfShootLayout" onClick={() =>
{type.onClickAction}((t) => !t)
}>
{type.name}
<i className={type.icon}></i>
</div>
</KindOfShootLayout>
))
}
I need to change the states toggle1 & toggle2 and also store the states and pass them to another component, I'm a little blocked
const [toggle1, setToggle1] = useState(true);
const [toggle2, setToggle2] = useState(true);
Solution 1:[1]
const KindOfShoots = [
{ id: 1, name: "Shoot in Studio",
link: "/Photoshoot",icon:"fa fa-calendar",
onClickAction: setToggle1 },
{ id: 2, name: "Shoot at other Location",
link: "/Photoshoot" ,icon:"fa fa-calendar",
onClickAction: setToggle2 },];
{
KindOfShoots.map((type)=>(
<KindOfShootLayout >
<div className="KindOfShootLayout" onClick={() => type.onClickAction(!toogle)}>
{type.name}
<i className={type.icon}></i>
</div>
</KindOfShootLayout>
))
}
Solution 2:[2]
Ok, I think I found an answer; I used the property onToggle
const KindOfShoots = [
{
id: 1,
name: "Shoot in Studio",
link: "/Photoshoot",
icon: "fa fa-calendar",
onToggle: setToggle1,
toggle: toggle1,
},
{
id: 2,
name: "Shoot at other Location",
onToggle: setToggle2,
toggle: toggle2,
link: "/Photoshoot",
icon: "fa fa-calendar",
},
];
And it returns
{KindOfShoots.map((type) => (
<KindOfShootLayout>
<div style={{display: toggleActual}}
className="KindOfShootLayout"
onClick={() => type.onToggle(!type.toggle)}
>
{type.name}
<i className={type.icon}></i>
</div>
</KindOfShootLayout>
))}
<div style={{ display: toggle1 ? "none" : "block" }}>
<ThirdGrandchild />
</div>
<div style={{ display: toggle2 ? "none" : "block" }}>
<SecondGrandchild />
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sakshi Mahajan |
| Solution 2 | Ojage S |
