Home > database >  How to make different variants of component based on props using styled MUI?
How to make different variants of component based on props using styled MUI?

Time:10-18

I'm trying to make my component looks different based on props like for example "variant" using styled function like below:

import { styled } from '@mui/material/styles';

const RemoveButton = styled(Button)(({ theme }) => ({
  backgroundColor: 'lightgreen',
}));

function App() {
  return (
    <>
      <RemoveButton>Remove Button</RemoveButton>
    </>
  );
}

export default App;

So for example what can I do if I want my component to be red when variant="contained" and blue when variant="outlined"?

CodePudding user response:

If you want to style the component based on its props using styled:

const RemoveButton = styled(Button)(({ variant }) => ({
  ...(variant === "contained" && {
    backgroundColor: "red"
  }),
  ...(variant === "outlined" && {
    backgroundColor: "blue"
  })
}));

You can also create your own custom variant using createTheme, see this answer for more detail.

CodePudding user response:

Okay, nevermind i figure it on my own idk is that recomended solution by mui but that works for me soo:

const RemoveButton = styled(Button)(({ theme, ...otherProps }) => ({
  backgroundColor: {"contained":"red","outlined":"green"}[otherProps.variant],
  padding: theme.spacing(1),
}));
  • Related