Home > Back-end >  How to select single sub item from every item in React Native
How to select single sub item from every item in React Native

Time:05-13

i am trying to select only one sub-item from every item like this photo: Flat list items with sub-items also in flatlist

what i am trying to do:

push an array with index:color, value:black.

when i choose red, to update array with: index:color, value:red.

and the CHECKBOX should be checked only with the selected sub-item (red or black).

this is my onPress function:

const [optionsSelected,setOptionsSelected] = useState([]);
const checkSelected = (optionid,valueid) =>{
  
  if(optionsSelected && optionsSelected.length>0){
    if(optionsSelected[optionid] && optionsSelected[optionid]!=undefined){
      
      optionsSelected[optionid]=valueid;
    }
  }else{
      setOptionsSelected(oldArray => [...oldArray, {[optionid]:valueid}]);
  }
}

CodePudding user response:

Why not use a plain object instead of an array?

setOptionsSelected(prev => ({
  ...prev,
  [optionid]: valueid,
});

CodePudding user response:

ok i found the solution:

first, this is the updated code:

const checkSelected = (optionid,valueid) =>{
  setOptionsSelected(oldArray => ({...oldArray,[optionid]:valueid}));
}

then, this is my check:

if(optionsSelected[item.option_id] && optionsSelected[item.option_id]==item.value_id){
        //checked=true;
      }else{
        //checked=false;
      }

thank you all.

  • Related