Is there an analog of Emotions 'css' function in MUI 5?

Viewed 1024

As I understand MUI 5 uses Emotion under the hood for styling, Emotion has this nice helper function css that looks like returns a string - a class name that you could use as a value for className or any other property.

import { css, cx } from '@emotion/css'

render(
  <div
    className={css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
    `}
  >
    Text
  </div>
)

I looked everywhere but could not find an analog available in MUI. There is css function in system and styled-engine but it does not seem to do the same, it returns SerializedStyles.

The use case I am looking to use it for is following:

I have a component that let's you to pass class-names (strings) for different parts of that component enabling you to change the component's styling. It seems like this css function (as shown in Emotion docs) could help me with this.

e.g.:

const headerStyle = css`
  color: blue;
  border-bottom: 1px solid red;
`;

<Component
  headerClassName={headerStyle}
  footerClassName={css`
    color: gray;
    font-size: 2rem;
  `}
/>

I guess I could solve it with makeStyles() but it is "legacy" not and the syntax shown on the screenshot above is more compelling to me.

1 Answers

You can create a wrapper of your Component and inject the style down from the parent component like below:

<Box sx={{
  '& .myHeader': {
    // your header styles
  },
  '& .myFooter': {
    // your footer styles
  },
}}>
  <Component
    headerClassName='myHeader'
    footerClassName='myFooter'
  />
</Box>

Or using styled:

import { styled } from "@mui/material/styles";

const headerClass = "header";
const footerClass = "footer";

const Container = styled("div")`
  & .${headerClass} {
    background-color: red;
  }
  & .${footerClass} {
    background-color: blue;
  }
`;

function Component({ headerClassName, footerClassName }) {
  return (
    <div>
      <div className={headerClassName}>h</div>
      <div className={footerClassName}>f</div>
    </div>
  );
}
<Container>
  <Component headerClassName={headerClass} footerClassName={footerClass} />
</Container>

Codesandbox Demo

Related