My initial goal to solve:
- I have 4 components lined up next to each other. I want to be able to toggle/onClick one of the components and have the other 3 components disappear. Then re-toggling that same component to have the other components reappear. But also have the ability to do the same task with toggling any of the other components.
- Each of components in simple terms is a div tag with an image tag within.
My initial take on the problem:
export const Test = () => {
const intialValue = [{id: 0, component: null}]
const array = [
{id: 1, component: <CompOne/>},
{id: 2, component: <CompTwo/>},
{id: 3, component: <CompThree/>},
{id: 4, component: <CompFour/>}
]
const [chosenNumber, setChosen] = useState(0)
const [statearray, setArray] = useState(array)
useEffect(() => {
console.log(chosenNumber)
const arr = array
if(chosenNumber === 0 ) setArray(array)
else setArray(arr.filter( num => num === chosenNumber))
}, [chosenNumber])
const handleClick = (number) => {
if(number === chosenNumber) setChosen(0)
else setChosen(number)
}
return (
<div className="flex" >
{statearray.map((comp, number) => <div key={number} className="h-12 w-12 bg-gray-400 m-1 flex items-center justify-center" onClick={() => handleClick(comp.id)}>{comp.id}</div>)}
</div>
);
}
My thought process is when I click the component (div), I'll set the chosenNumber, if the div I clicked is the same as chosen, reset chosen to zero.
Every time the chosenNumber changes, useEffect should detect it and filter the array with chosenNumber, if chose is zero, reset stateArray.
Right now when I click one of the components, they all disappear. I am just not sure if using zero is the right thing to use to compare each object or what I need to use instead.
Thanks for the help!