Home > Back-end >  How can I pass the props to styled component(Button) in MUI?
How can I pass the props to styled component(Button) in MUI?

Time:07-19

I am creating custom button from Button component using styled.

export const CustomButton = styled(Button)({
  borderRadius: "17px",
  fontWeight: 300,
  fontSize: ".8125rem",
  height: "34px",
  lineHeight: "34px",
  textAlign: "center",
  padding: "0 25px",
  transition: "all .15s ease-in-out",
  "&:hover": {
    transform: "scale(1.05)",
    opacity: 1,
  }
});

I want to pass some data as a props such as background color or text color.

<CustomButton bgColor="red">Custom Button</CustomButton>

How can I use the passed data when defining the styled component? I saw several similar topics but all answers were using `` syntax instead of the function one.

CodePudding user response:

You can pass a callback as the second argument to your component that will take the additional props passed and can be used to set additional styles. Pass the additional props as a type or interface in angled brackets after the call to styled()

interface CustomButtonProps {
    bgColor: string
}

export const CustomButton = styled(Button)<CustomButtonProps>(
    {
        // ...
    },
    ({ bgColor }: CustomButtonProps) => ({
        backgroundColor: bgColor,
    })
);

CodePudding user response:

Your Button component can be a MUI Button or a custom button.

import Button from '@mui/material/Button';

or

import styled from "styled-components";

const Button = styled.button`
  font-size: 0.8125rem;
  ...
`;

If it is a custom button, you have to make sure that the button is created by using style-components. Otherwise, it will not work.

Then you can use it like this:

export const CustomButton = styled(Button)<{ bgColor: string }>(
  ({ bgColor }) => {
    return {
      backgroundColor: bgColor,
      borderRadius: "20px",
      fontWeight: 300,
      fontSize: ".8125rem",
      height: "34px",
      lineHeight: "34px",
      textAlign: "center",
      padding: "0 25px",
      transition: "all .15s ease-in-out",
      "&:hover": {
        transform: "scale(1.05)",
        opacity: 1,
      },
    };
  }
);

and the javascript version:

export const CustomButton = styled(Button)(({ bgColor }) => {
  return {
    backgroundColor: bgColor,
    ...
  }
});

CodePudding user response:

Here is a simple example based on your question using styled components to pass the bgcolor and fontsize props .

import styled from '@emotion/styled';

interface CustomButtonProps {
  bgcolor: string;
  fontcolor: string;
}

const CustomButton = styled(Button)`
  background: ${({ bgcolor }: CustomButtonProps) => bgcolor};
  color: ${({ fontcolor }: CustomButtonProps) => fontcolor};
`;

  <CustomButton bgcolor="red" fontcolor='green'>Test button</CustomButton>
  • Related