How to re-use styles for components using the sx props with React and Material UI
A really simple way to create reusable components using sx
for styling looks like this:
First of all, once you realize that you are creating a similar component more than twice, then it's a good time to create a component with some default properties and then you add some additional properties to make the differentiation, and a quick example would look like this:
import { Chip } from '@mui/material';
type ChipLabelGuidelineProps = {
label: string;
borderColor?: string;
bgcolor?: string;
padding?: string;
//..rest of your attributes if you use them directly
}
const ChipLabelGuideline = (props: ChipLabelGuidelineProps) => {
const { label, borderColor = 'white', ...restSxProps } = props;
return (
<Chip
label={label}
sx={{
borderRadius: '8px',
fontSize: '16px',
fontWeight: '700',
border: `2px solid ${borderColor}`,
padding: '4px 25px',
color: 'blue',
...restSxProps,
}}
/>
);
};
Then you can use it like this:
<ChipLabelGuideline label="Label 1" bgcolor='green' />
# Or
<ChipLabelGuideline label="Label 2" bgcolor='black' />
# or if you want to override some data
<ChipLabelGuideline label="Label 3" bgcolor='yellow' color='white' padding: '0 10px'/>
Really simple isn't it?