Search code examples
reactjsstorybook

State of Dynamically Generated Radio Buttons


I'm trying to pass a class only to the checked radio button in my component, but with my existing code all the radio buttons receive the class. Any advice?

export default function RadioGroup({options}){
  
  const [isChecked, setIsChecked] = useState(false);
  
  return(
    <>
      {options.map(option => {
        return (
          <Radio
            radioID={option.id}
            radioName={name}
            radioLabel={option.label}
            radioClass={` ${isChecked ? "bg-blue" : ""}`}
            onChange={() => setIsChecked((prev) => !prev)}
          />
        )
      })}
    </>
  );
}

Solution

  • Instead of passing Boolean in setIsChecked, you have to pass the id then you can add the bg-blue class on id base, as you can see the below code.

    export default function RadioGroup({options}){
      
      const [isChecked, setIsChecked] = useState(null);
      
      return(
        <>
          {options.map(option => {
            return (
              <Radio
                radioID={option.id}
                radioName={name}
                radioLabel={option.label}
                radioClass={` ${(isChecked === option.id) ? "bg-blue" : ""}`}
                onChange={() => setIsChecked(option.id)}
              />
            )
          })}
        </>
      );
    }