How to select only one MUI ToggleButton within a ToggleButtonGroup when mapping through an array with an unknown length

Viewed 42

I am using MUI and React to display fixtures (home, draw, away) as a ToggleButton that can be selected. I'd like to have only one selection per row. The fixtures change each week, including the number of fixtures.

Per default ToggleButtonGroup allows one selection for all fixtures.

I changed the exclusive prop to false which takes an array but then the user can select multiple result per row, which isn't what I'm trying to achieve.

How can I add logic for only one item per row to be selectable?

Note: The fixtures are returned from a database call. I added in the fixtures array as an example of what is returned from the database call.

How the fixtures appear with ToggleButtons

const [fixtures, SetFixtures] = useState([{
    gameweek: "loading...", game: "loading...", home: "loading...",
    away: "loading...", draw: "loading...", kickoff_datetime: "loading...", result: "loading...",
  }]);
const [alignment, setAlignment] = useState([]);


const handleChange = (newAlignment) => {
    setAlignment(newAlignment);
  };


const fixtures = [
      { game: "LeicesterArsenal", gameweek: 2, home: "Leicester", away: "Arsenal", draw:"LeicesterArsenalDraw", kickoff_datetime: "2022-07-15T15:30:00", result: null }, 
      { game: "ManchesterUnitedNottinghamForest", game: 2, home: "Manchester United", away: "Nottingham Forest", draw:"ManchesterUnitedNottinghamForestDraw", kickoff_datetime: "2022-07-15T15:30:00", result: null }, 
      { game: "TottenhamWestHam", game: 2, home: "Tottenham", away: "West Ham", draw:"TottenhamWestHamDraw", kickoff_datetime: "2022-07-15T15:30:00", result: null }, 
      { game: "WolvesCrystalPalace", game: 2, home: "Wolves", away: "Crystal Palace", draw:"WolvesCrystalPalaceDraw", kickoff_datetime: "2022-07-15T15:30:00", result: null }]


function RenderFixtures() {
    return fixtures.map((fixture, index) =>
      <div id={"fixture-row-" + index} key={fixture.game}>
      <ToggleButtonGroup
        color="success"
        value={alignment}
        exclusive={true}
        onChange={handleChange}
      >
        <ToggleButton value={fixture.home}>{fixture.home}</ToggleButton>
        <ToggleButton value={fixture.draw}>Draw</ToggleButton>
        <ToggleButton value={fixture.away}>{fixture.away}</ToggleButton>
        </ToggleButtonGroup>
      </div>
0 Answers
Related