Skip to content

Make state related index make true while other state always false

  const [isItemExpand, setIsItemExpand] = useState([{ ind: 0, isExpand: false }])

this is my function to make related state true

 const handleExpand = (i: number) => {
     const newList = [...isItemExpand]
     newList[i] = { ind: i, isExpand: !isItemExpand[i].isExpand }
     setIsItemExpand(newList)
 }

I need to make index related state true while at the same time states not equal to index need make false, How can I achieve that in the same function above

as a example – in current condition, if I expand (index 1), then expand (index 2) my array looks like

0: {ind: 0, isExpand: false}
1: {ind: 1, isExpand: true}
2: {ind: 2, isExpand: true}
3: {ind: 3, isExpand: false}

but after expanding (index 2) I expect array like this

0: {ind: 0, isExpand: false}
1: {ind: 1, isExpand: false}
2: {ind: 2, isExpand: true}
3: {ind: 3, isExpand: false}

to achieve this i need to reset all other states to false expect which matches with index

Answer

If I understand the goal correctly – that only one element should have isExpand = true – then you can map the items and set false or true depending on the ind condition

const handleExpand = (i: number) => {
  const newList = isItemExpand.map((item) => ({ ...item, isExpand: item.ind === i }));
  setIsItemExpand(newList);
};

updated

const handleExpand = (i: number) => {
  const newList = isItemExpand.map((item) => 
    ({ ...item, isExpand: (item.ind === i) ? !item.isExpand : false });
  setIsItemExpand(newList);
};