Dynamically control state over a group of buttons?

I know how to setup a separate state variable for the buttons below, if hardcoded inside return().

What I don’t know how to do is handle state for an dynamic number of buttons creating by mapping an array.

Am I on the right track with refs? The goal is to assign 1 class to all buttons, and a special ‘active’ class to the most recently clicked button.

export default function SpeedControls(props: { setInterval: Function }) {
  const [selectedButton, setSelectedButton] = useState<any>();
  const { setInterval } = props;

  const controlValues = [
    { milliseconds: 1000, label: '1x', ref: useRef('1x') },
    { milliseconds: 750, label: '1.5x', ref: useRef('1.5x') },
    { milliseconds: 500, label: '2x', ref: useRef('2x') }
  ];

  useEffect(() => {
    // set all buttons to nothing

    // set the selected button only to class active
    selectedButton?.classList.add('active');
  });

  return (
    <div>
      { controlValues.map(buttonConfig => (
        <button
          key={buttonConfig.label}
          onClick={() => { 
            setInterval(buttonConfig.milliseconds);
            setSelectedButton(buttonConfig.ref.current)
          }}
          className='control-button'
        >
          {buttonConfig.label}  
        </button>
      )) }
    </div>
  )
}

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.