Can MUI 5 replicate the Emotions 'css' function through analog?

From what I've learned, MUI 5 utilizes Emotion for its styling framework. Emotion offers a convenient helper function called css, which generates a string - a class name that can be used as a value for the className property or any other relevant property.

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

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

I've searched extensively but couldn't find an equivalent in MUI. While there is a css function in system and styled-engine, it doesn't function similarly as it returns SerializedStyles.

The scenario where I aim to utilize it is as follows:

I have a component that allows you to pass class names (as strings) for different parts of that component, enabling flexibility in changing the component's styles. It seems like this css function (as demonstrated in the Emotion documentation) could assist with this.

For example:

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

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

Although I could potentially resolve it using makeStyles(), the syntax presented in the screenshot above appeals more to me than the "legacy" solution.

Answer №1

To incorporate styles into your Component, you can create a wrapper and pass the style down from the parent component as shown below:

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

Another option is to use 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>

https://codesandbox.io/s/69262127-is-there-an-analog-of-emotions-css-function-in-mui-5-k78uz?file=/demo.tsx

Answer №2

import { ClassNames } from '@emotion/react';

export const CustomComponent = ({ customClassName, styles, ...otherProps }) => (
  <ClassNames>
    {({ css, cx }) => (
      <div className={cx(customClassName, css(styles))} {...otherProps} /> 
    )}
  </ClassNames>
);

Example of how to use:

<CustomComponent styles={{ color: "green" }} customClassName="someCustomClass">text</CustomComponent>

You can also apply css() function to customClassName:

<div className={cx(css(customClassName), css(styles))} {...otherProps} /> 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The collapse button in Bootstrap 3.3 and jQuery 1.1 appears to be visible but unresponsive when clicked

This code isn't functioning properly as it displays the three horizontal bar button, but nothing happens when clicked. bootstrap-3.3 jquery-1.1 Toggle navigation CopyHere <div class="collap ...

Issue with Datepicker functionality within the <th> element is causing it to malfunction

Currently, I am attempting to utilize the Bootstrap datepicker, but I am facing an issue when trying to implement it within a table, specifically inside a th element. Below is the structure of my table: <table id="table" class="table table-bord ...

The markers on Google Maps are currently displaying in the wrong position, despite the latitude and longitude being correct

Utilizing the Google Maps API, I have implemented a system to dynamically add map markers tracking 2 of our company's vehicles. The website is developed in asp.net c# mvc with bootstrap 4.3.1. An ajax request retrieves the latest marker location from ...

What is the best way to apply a conditional class to multiple elements with jQuery?

Hey there, I'm new here so please forgive any mistakes I might make or if I break any etiquette rules! I'm trying to create some cool buttons for radio inputs on a form using field yields. The idea is to have them start off in grayscale and then ...

What are the steps to adjust the width of a website from the standard size to a widescreen

Is it possible to create a "floating" screen adjustment on websites? I know you can set the standard size of pixels, but how do sites adjust for different screen sizes like wider laptop screens? Does it automatically detect the reader's screen size an ...

Adjust the number of images in each row based on the width of the screen

I have experimented with various methods, but none seem to work flawlessly. My goal is to neatly display around 50 images in rows and columns, adjusting the length of each row based on the screen width. Here are the approaches I've tried: Placing ...

Issues with Autofocus while Searching and Selecting from Dropdown menu

Here is the JavaScript code I am using: <script type="text/javascript"> function handleSelectionChange(selectElement, nextField) { nextField.focus(); } function handleKeyPress(event, currentField, nextField) { i ...

"Exciting update for Android users: Chip background color transforms with the use of BottomSheet Material 3

Here is the chip XML code snippet I am working with: <com.google.android.material.chip.Chip android:id="@+id/income_type_chip" android:layout_width="0dp" style="@style/Widget.Material3.Chip.Filter" android:l ...

How can I create an input field in MUI that restricts input to letters, numbers, and dashes

Is there a way to configure an MUI input field so that it only accepts letters, numbers, and dashes while excluding spaces and symbols such as (*&^%$#@!,.<>{}[])? Specifically, I want to allow characters that wouldn't disrupt a URL, like . Tha ...

Maintain the previous droppable positioning after refreshing the page

I am encountering an issue with the .droppable event. I have set up two sections where I can move elements, but every time the page is refreshed, the positioning of the elements reverts to the initial position. How can I maintain the last positioning of th ...

Bring the element to the top of the page by clicking on the anchor within the element or anywhere within the specified div ID

I am looking to implement a functionality where the page scrolls to the top of the navigation div ID when a link inside the navigation div is clicked, or ideally even when clicking anywhere within the div itself that contains the navigation links. After r ...

The parent element is not able to apply the CSS text-decoration in jQuery

Is there a way to retrieve a specific CSS property of an element, even if it is inherited from its parent? The standard jQuery method .css() can help with this. Consider the following HTML structure: <div id="container"> some text<br> ...

Adding an additional border when combining two divs with rounded borders

I attempted to create a design similar to the Instagram "ask me a question" box, but I am encountering an issue where there is some extra border around the title when the two divs merge. What am I doing incorrectly? .info { overflow: hidden; ...

Difficulty with setting a border for text spanning multiple lines

I am trying to style a header text with a border around it. The issue arises when the larger text spans over two lines, causing the border to break in between. In an attempt to fix this, I applied the CSS property box-decoration-break: clone;. However, thi ...

What is the process for adding a Background Image in Nextjs?

In my current project, I am utilizing Nextjs and Material-UI. However, I have encountered an issue when trying to set a background image compared to previous projects using React. As this is my first time working with Nextjs, I attempted importing Image ...

Customizing the colors of the Input field in the Material UI Text Field component with CSS styling can elevate the overall

import { TextField } from "@mui/material"; import { FunctionComponent } from "react"; interface IProps { type: string; label: string; color: | "error" | "primary" | "secondary" | &quo ...

What is the best way to ensure that text highlighting appears consistent on all browsers?

I am facing an issue with the appearance of text highlighting between Chrome and Firefox browsers. Is there a way to ensure consistency in the appearance across all browsers? a { text-decoration: none; font-weight: 900; font-size: 4vw !impo ...

Tips for executing a function in the HC-Sticky plugin?

Currently, I am utilizing the HC-Sticky JavaScript plugin and endeavoring to utilize the documented reinit method. However, I am facing difficulty in understanding how to execute it. In this CodePen demo, a basic setup is displayed along with an attempt t ...

Align text divs vertically and ensure font size is responsive within a container div

Within this designated div, I have included: https://i.stack.imgur.com/j099H.png In an attempt to ensure that the font size of the text adjusts responsively, I implemented the following code: font-size:calc(xx + 1.5vw); However, upon resizing the scree ...

Give the Row ID as a parameter to a personalized component within MUI Datagrid Pro

I am currently exploring the idea of incorporating an intermediate state to row checkboxes based on the selection status of other checkboxes within a detailed panel. My approach involves crafting a custom checkbox component and implementing some logical ...