Search code examples
reactjsstorybook

Setting Radio Group Checked Status


I'm building a component for a group of radio buttons that sets a class on the checked radio component.

export default function RadioBlockGroup({
  options,
  radioName,
  isChecked
}){
const [radioIsChecked, setIsChecked] = useState(isChecked);
  return(
    {options.map((option, i) => {

      return (
        <Radio
          key={i}
          radioID={option.radioID}
          radioName={radioName}
          radioLabel={option.radioLabel}
          radioClass={`${(radioIsChecked === option.radioID) ? "active" : ""} `}
          onChange={() => setIsChecked(option.radioID)}
          isChecked={option.isChecked}
          />
      )
    })}
  );
}

This works great, unless I set one of the radio buttons to be "checked" - doing so breaks the ability to click and change the selected radio button.

radioName: "radio-blocks",
options: [
  {
    radioID: "1",
    radioLabel: "One",
  },
  {
    radioID: "2",
    radioLabel: "Two",
    isChecked: true,
  }
]

What am I missing?


Solution

  • Simple answer: you are hard-coding the isChecked attribute so that no matter what button you click the option with isChecked property set to true will always be the one selected. So try doing this

    export default function RadioBlockGroup({
      options,
      radioName,
      isChecked
    }){
    const [radioIsChecked, setIsChecked] = useState(isChecked);
      return(
        {options.map((option, i) => {
    
          return (
            <Radio
              key={i}
              radioID={option.radioID}
              radioName={radioName}
              radioLabel={option.radioLabel}
              radioClass={`${(radioIsChecked === option.radioID) ? "active" : ""} `}
              onChange={() => setIsChecked(option.radioID)}
              isChecked={radioIsChecked === option.radioID}
              />
          )
        })}
      );
    }