I have a main component which has two child components and six of each.
Something like this:
<Main>
<Component1 />
<Component1 />
<Component1 />
<Component1 />
<Component1 />
<Component1 />
<Component2 />
<Component2 />
<Component2 />
<Component2 />
<Component2 />
<Component2 />
</Main>
My goal is to be able to render a specific Component2 based on a toggle from Component 1.
So clicking the first Component1 would toggle the render of the first Component2
I've tried something like this in my main component:
const [component2Visible, setcomponent2Visible] = useState([false, true, false, false, false, false])
But I don't think this is the right direction at all.
Here is an approach that I might employ:
// state variables to hold arguments to generate Component1 & Component2
// Component1 args have a prop named 'hideC2' (initially set to false)
const [comp1Args, setComp1Args] = useState([{hideC2: false, ...}, {hideC2: false, ....}, {}]);
const [comp2Args, setComp2Args] = useState([{}, {}, {}]);
.
.
.
// Iterate over the two args arrays to generate Components
// Use '.filter' on comp2Args to 'hide' those where 'hideC2' is set to true
return (
<Main>
{
comp1Args.map((args, idx) => (
<Component1
key={idx}
args={args}
onToggleC2={() => setComp1Args(prev => {
const curr = [...prev];
curr[idx].hideC2 = !prev[idx].hideC2;
return [...curr]
})}
/>
))
}
{
comp2Args
.filter((el, idx) => (comp1Args[idx].hideC2 !== true))
.map((args, idx) => (
<Component2 key={idx} args={args}/>
))
}
</Main>
);