mui/material-ui

Support passing theme into `css()` (or its wrapper) from `'@emotion/react'`

Opened this issue · 3 comments

Summary

According to the documentation (one, two, three), passing the theme is currently only supported when using styled() from '@mui/material/styles' (which, to my understanding, is a wrapper over styled() from '@emotion/styled'). However, there's no similar wrapper for css() that would allow passing the theme as well. Adding this wrapper would simplify code in some cases, removing the need to create additional wrappers around React components.

Examples

Note: in the following example sx={{m: 1}} would suffice, but imagine you need the classname or SerializedStyles here

Current

const StyledBox = styled(Box)(({ theme }) => ({
    margins: theme.spacing(1)
}))

function MyComponent() {
    return <StyledBox/>
}

Proposed

function MyComponent() {
    return (
        <Box
            css={css(({ theme }) => ({
                margin: theme.spacing(1)
            }))}
        />
    )
}

Motivation

Using css() is sometimes preferred because it eliminates the need for an additional identifier (e.g., StyledBox) in the search scope. The inability to pass the theme limits its usage to cases where the theme is not needed, which can be surprising since libraries like tss-react, JSS, and Pigment allow passing the theme to similar utilities. Supporting this functionality for Emotion's css() would close this gap.

Search keywords: css, emotion, theme

Thanks for the feedback. cc @romgrk

I guess it's' not there in @mui/material/styles because it's not there in @emotion/css since it does not rely on ThemeProvider which comes from @emotion/react.
So getting theme value within the css() call might not be possible in it's current API usage.
We should discuss it internally first.

romgrk commented

Is this a different use-case than just passing a function to sx?

function MyComponent() {
    return (
        <Box
            sx={({ theme }) => ({
                margin: theme.spacing(1)
            })}
        />
    )
}