Home > Software design >  Fill active button with color on buttions that are dynamically created
Fill active button with color on buttions that are dynamically created

Time:04-14

I am trying to get a button to say active when pressed, the problem is how would I do with buttons that are dynamically created?

Currently I have it is set up like this:

      <Grid container sx={{ padding: "10px" }}>
        {Object.values(CATEGORIES).map((c) => {
          return (
            <Button className="category-btn" onClick={() => handleChange(c)}>
              {c.title}
            </Button>
          );
        })}
      </Grid>

Since the buttons are being dynamically generated I am not sure how to add the functionality. I have currently tried this answer to an avail.

Change color of active button among multiple buttons in React using material ui

CodePudding user response:

If the CATEGORIES object doesn't have an id, the map function give you also the index in the array that you can track to discover which button should be active.

If you can have only one button active:

const [activeButtonIndex, setActiveButtonIndex] = useState(null)

const handleChange = (c,index) => {
  setActiveButtonIndex(index)
}
...
<Grid container sx={{ padding: "10px" }}>
        {Object.values(CATEGORIES).map((c,index) => {
          return (
            <Button className={index === activeButtonIndex ? "category-btn-active" : "category-btn"} onClick={() => handleChange(c,index)}>
              {c.title}
            </Button>
          );
        })}
      </Grid>

if you can have multiple button active you can:

const [activeButtonIndexList, setActiveButtonIndexList] = useState([])

const handleChange = (c,index) => {
  setActiveButtonIndexList([...activeButtonIndexList, index])
}
...
<Grid container sx={{ padding: "10px" }}>
        {Object.values(CATEGORIES).map((c,index) => {
          return (
            <Button className={activeButtonIndexList.includes(index) ? "category-btn-active" : "category-btn"} onClick={() => handleChange(c,index)}>
              {c.title}
            </Button>
          );
        })}
      </Grid>
  • Related