When using Material UI styled utility sometimes we need to render custom styles depending on props passed to the components, for example change the color based on a boolean prop called selected, if selected is true the background should be blue if not background should be red
We are going to pass properties from the component to our styled component and use custom css rules depending on the value passed to the styled component
// ./components/CustomButton.tsx
import React from "react";
import { Button, ButtonProps, styled } from "@mui/material";
// Props defined to use on new custom component, we extend ButtonProps to have access to MUI Button props
interface StyledButtonProps extends ButtonProps {
selected?: boolean;
}
// Create styled component using parameters to defined css rules
const StyledButton = styled(Button)<StyledButtonProps>(({ selected }) => ({
background: selected ? "blue" : "red",
color: "white",
"&:hover": {
background: "blue",
},
}));
export const CustomButton = ({
selected,
onClick,
children,
}: {
selected: boolean;
onClick: () => void;
children: JSX.Element;
}) => {
return (
// Pass selected prop to our new component
<StyledButton selected={selected} onClick={onClick}>
{children}
</StyledButton>
);
};
This is an example of how to use our component
// ./index.tsx
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { CustomButton } from "./components/CustomButton";
function App() {
const [selected, setSelected] = useState(false);
return (
<span>
<CustomButton
onClick={() => {
setSelected(true);
}}
selected={selected}
>
<span>Test</span>
</CustomButton>
</span>
);
}
ReactDOM.render(<App />, document.querySelector("#app"));
You can find a CodeSandbox with the implementation on the following link https://codesandbox.io/p/sandbox/tkzdnf