Skip to content
Advertisement

Handling mutiple radio-button-groups with useState

I have this renderUpgrades-function in which the options of an item get included into radio-button-groups. So an item has multiple options where each option has a a radio-button-group. I know that a radio-button-group can be handled with useState where each useState gets a group assigned. But in my case I don’t know how many options an item has so I can’t initialize the exact amount of useStates at the beginning. Is there a way how I can initalize the useStates depending on how many options there are or is there another way how the radio-button-goups can be handled?

const renderUpgrades=(item)=>{
        return item.optionModules.map((optionModule,index)=> {
            console.log(optionModule.module)
            if (optionModule.module && optionModule.module.selectionRequired) {
                return(
                    <div key={index}>
                        <h4>{optionModule.module.name}</h4>
                        {optionModule.module.options.map((moduleOptions) => {
                            if(optionModule){
                                return (
                                    <div onChange={()=>{}}>
                                        <label><input type="radio" value={moduleOptions.option.name} name={index} checked={moduleOptions.isDefault}/>   {moduleOptions.option.name}</label>
                                    </div>
                                )
                            }else{
                                return console.log("No shifts applied");
                            }
                        })
                        }
                    </div>
                )
            }})
    }

Advertisement

Answer

You can use an object as state.

const [radioGroups, setRadioGroups] = useState({});

The initialization can be done separately, for example in a useEffect with empty dependency array:

useEffect(() => {
  const groups = {};
  // Loop through your radio groups here, I don't think I got the right array
  item.optionModules.forEach(module => {
    groups[module.option.name] = "default selected value";
  });

  setRadioGroups(groups);
}, []);

Then everytime you have to edit a group you get the current state and edit the group

setRadioGroups({ ...radioGroups, [groupToBeChanged]: groupValue });
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement