简体   繁体   中英

React JS Toggle Selected Item

I'm using react hooks, state within my component. A list of options is available to the user to select. I need tokeep track of which options have been selected - see "selectedArr" in state.

Whilst this partially works, filtering the selectedArr is buggy and won't filter if I select the second item in the options first? I don't understand why.

How can I keep track of which options are selected and toggle an individual option?

Here is my code

const BarGraph = ({graphData, daysRange}) => {
const [optionsIndex, setOptionsIndex] = useState(0);
const [selectedArr, setSelectedArr] = useState([]);


const toggleActiveItem = (index) => {
    //Update the option index 
    setOptionsIndex(index);

    //Update selected options array
    setSelectedArr([...selectedArr, index]) 

    if(index === selectedArr[index]) {
        //Prevent from adding multiple of the same index
        setSelectedArr([...selectedArr])

        //if index is equal to the selected array index 
        //removed the matched index from selected array
        setSelectedArr(selectedArr.filter((i) => i !== index)); 
    }

}
const toggleActiveItem = (index) => {
    
    if(selectedArr.includes(index)){
      setSelectedArr(selectedArr.filter((i) => i !== index)) 
    } else {
     setSelectedArr([...selectedArr, index]) 
    }

    setOptionsIndex(index)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM