score:4

Accepted answer

one way to do this is to use array map with index like this:

import react, { usestate } from "react";
 
export default function app() {
  const days = ['monday', 'tuesday', ... ]
  const [activeindex, setactiveindex] = usestate(-1); 
  const handletoggle = (index) => {
    setactiveindex(index);
  };
  return (
    <div > 
{days.map((day, index) => (
      <button onclick={()=> handletoggle(index)}  classname={activeindex === index ? "active" : null}>{day}</button> 
)
    </div>
  );
}

score:1

you can extract your button-props to a function if the markup gets a bit longwinded

export default function app() {
  const [chosen, choose] = react.usestate();

  const makeprops = (name) => ({
    onclick: () => choose(name),
    classname: chosen === name ? 'active' : null
  })

  return (
    <div classname="app">
      <button {...makeprops('one')}>one</button>
      <button {...makeprops('two')}>two</button>
      <button {...makeprops('duck')}>duck</button>
    </div>
  );
}

or encapsulate the entire behaviour to its own 'buttonthatcanbeactive' component that takes a "active" and "onclick" prop

score:4

assuming you have a src/index.css file that contains the required css class... your current script will assign the "active" class to all buttons at once. to apply the class to a single button you need to have an object in state like so:

const [daysactive, setdaysactive] = usestate({ monday: false, tuesday: false... });

and in your toggle method you will pass the day key as such:

const handletoggle = (day) => {
  setdaysactive({
    ...daysactive,
    [day]: !daysactive[day]
  });
}

so a jsx button will call this handler with its respective day key

<button onclick={() => handletoggle("sunday")} classname={daysactive["sunday"] ? "active" : null}>sunday</button>

if you'd like to make this button set cleaner you can use the map function

const days = ["sunday", "monday", ...];

<div>
  {days.map((day) => (
    <button ... />
  ))}
</div>

Related Query

More Query from same tag