简体   繁体   中英

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

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" ?

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.

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),
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM