mui / material-ui

Material UI: Comprehensive React component library that implements Google's Material Design. Free forever.
https://mui.com/material-ui/
MIT License
94.03k stars 32.31k forks source link

Allow overriding props in styled #44456

Open aqeelat opened 6 days ago

aqeelat commented 6 days ago

Summary

When created reusable components, it is often very helpful to pass default props to the component. Adding props to interface MuiStyledOptions will allow the users to set these props.

Examples

One use case: Creating a reusable outlined button with extra css. Instead of doing:

export const FullWidthOutlinedButton = styled(Button)(({ theme }) => ({
  width: '100%',
  marginTop: theme.spacing(5),
}))

and always remembering to add the variant when using the component, we can do this:

export const FullWidthOutlinedButton = styled(Button, {props: {varient: "outlined"}})(({ theme }) => ({
  width: '100%',
  marginTop: theme.spacing(5),
}))

I know the css here is generic but the possibilities are endless

Motivation

Improving DX when creating reusable components, and minimizing human error

Search keywords: props defaults custom

aarongarciah commented 3 days ago

Hey @aqeelat, thanks for your interest. For your use case, I recommend creating your own wrapper component to apply default props, something like this:

const FullWidthOutlinedButton = styled(Button)(({ theme }) => ({
  width: '100%',
  marginTop: theme.spacing(5)
}))

const FullWidthOutlinedButtonWithDefaults = (props) => {
  // Provide default variant
  const { variant = 'outlined', ...rest } = props;

  return <ExtendedButton variant={variant} {...rest} />;
};