Home > Net >  Apply variant on styled component
Apply variant on styled component

Time:07-19

I have created a styled button in mui. In component, I added styles and it is working. But I want to add "Variant" in Styled Component instead of adding it in button attribute while using it.

// StyledButton.js

import styled from "@mui/system/styled";
import Button from "@mui/material/Button";

const StyledButton = styled(Button)({
  width: 100,
  fontSize: 12,
  textTransform: "none",
 // variant: "contained" // something like this
});

export default StyledButton;

// App.js

import StyledButton from "./StyledButton";

export default function App() {
  return (
    <div>
     {/* Instead of 'variant' property */}
      <StyledButton variant="contained">Add App</StyledButton>
    </div>
  );
}

Instead of <StyledButton variant="contained">Add App</StyledButton>

I want to use like below

const StyledButton = styled(Button)({
   variant: "contained" // something like this
});

so that the button declaration will be as below.

<StyledButton>Add App</StyledButton>

codesandbox link

CodePudding user response:

Try this change your style based on requirement and also change variant name as per your need and give your style.

codesandbox link: https://codesandbox.io/s/styled-button-variant-mui-sofl-forked-1dq8tn?file=/src/StyledButton.js

CodePudding user response:

You can pass the variant prop to the styled MUI button

export const StyledButton = styled(Button)(({ variant }) => ({
  ...(variant === "special" && {
    width: 100,
    fontSize: 12,
    textTransform: "none"
  }),
  ...(variant === "outlined" && {
    backgroundColor: "blue"
  })
}));

CodeSandBox : https://codesandbox.io/s/styled-button-variant-mui-sofl-forked-bycbv6?file=/src/StyledButton.js:85-318

  • Related