MUI ToggleButton set selected background-colour dynamically

Viewed 206
const StyledToggleButton = styled(MuiToggleButton)(({ selectedColor }) => ({
    "&.Mui-selected, &.Mui-selected:hover": {
        backgroundColor: selectedColor,
    }
}));
const FilterTeam = (props) => {
  const [view, setView] = useState(1);
  const handleChange = (event: any, nextView: any) => {
    setView(nextView);
  };

  return (
   <ToggleButtonGroup
    orientation="horizontal"
    value={view}
    exclusive
    onChange={handleChange}
   >
    { Object.values(teams).map((teamObject: any, index) =>
     <StyledToggleButton
      key={teamObject.team}
      className={classes.toggleButton}
      value={teamObject.team}
      selectedColor={teamObject.colorTheme}
     >
      <img className={classes.teamLogo}
        alt="team logo" src={teamObject.logo} />
     </StyledToggleButton>
    )}
   </ToggleButtonGroup>
  );
}

export default FilterTeam

I keep getting:Warning: React does not recognize the selectedColorprop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercaseselectedcolor instead. If you accidentally passed it from a parent component, remove it from the DOM element.. I have gone over a couple sandbox which implement the same but I am trying it on typescript so I am not sure how it converts. I have referred to https://codesandbox.io/s/69707814-set-selected-color-of-toggle-button-group-mui-5l5lh?file=/demo.js

1 Answers

You can use the shouldForwardProp option to styled to prevent the selectedColor prop from being forwarded through to ToggleButton (which then passes it along to the DOM element).

const ToggleButton = styled(MuiToggleButton, {
  shouldForwardProp: (prop) => prop !== "selectedColor"
})(({ selectedColor }) => ({
  "&.Mui-selected, &.Mui-selected:hover": {
    color: "white",
    backgroundColor: selectedColor
  }
}));

Edit 69707814/set-selected-color-of-toggle-button-group-mui (forked)

Emotion documentation: https://emotion.sh/docs/styled#customizing-prop-forwarding

Related answer: @mui/system -- how to pass transient props to styled()

Related