Wt.N
Wt.N

Reputation: 1658

Is it possible to pass props to MUI styled() component?

Is it possible to pass default props to a style component? For example, I want to make a component with using Typography from MUI.

const H1Typography = (props) => (
  <Typography variant='h1' sx={{fontWeight: 500}}>{props.children}</Typography>
)

How can I add variant props into the below mui styled component?

const H1Typography = styled(Typography)(({theme}) => ({
  fontWeight: 500
}))

https://mui.com/system/styled/

Upvotes: 3

Views: 3307

Answers (2)

hane Smitter
hane Smitter

Reputation: 880

Incase you want to pass your own custom props to a styled component without getting include in the HTML DOM, you can checkout https://stackoverflow.com/a/75750276/11966906.
However reading your question seems like you want to pass the variant prop which internal to material-ui. In this case, simply pass the variant prop like:

// Created as
const H1Typography = styled(Typography)(({theme}) => ({
  fontWeight: 500
}))
// Use as
const MyComponent = (props) => (
  <H1Typography variant='h1' sx={{fontWeight: 500}}>{props.children}</H1Typography>
)

Upvotes: 0

JeCr
JeCr

Reputation: 77

You can pass it like you pass theme, but if you use a boolean prop you will receive an error.

const H1Typography = styled(Typography)(({theme, huge}) => ({fontWeight: 500,fontSize: huge === "true" ? "4rem" : "1rem"}))

Note, that I pass the huge prop as a string.

Upvotes: 2

Related Questions