MUI version 5 - Keep styling separate from component files

Seeking to segregate styling from component File in MUI v5. In the past, I accomplished this in v4 by utilizing makeStyles as shown below:

Page.style.js:

import { makeStyles } from "@material-ui/core";

export const useStyles = makeStyles({
  root: {
    background: "white",
  },
});

Page.js:

import React from "react";
import useStyles from "./Page.style";

const Page = () => {
  const classes = useStyles();
        
  return (
    <div className={classes.root}></div>
  )
}

makeStyles is now considered legacy and slated for deprecation in future versions. What is the recommended approach for separating styling and components into distinct files in v5?

Answer №1

In version 5 of our framework, the recommended styling APIs are styled()/sx prop. Using the styled function allows you to create a reusable styled component for separating styling code. On the other hand, the sx prop is more suitable for inline one-off styles and may not be the best option for this situation:

const Div = styled('div')({
  background: "white",
});

export Div;
import React from "react";
import { Div } from "./Div";

const Page = () => {
  return (
    <Div />
  )
}

Furthermore, in MUI v5, you can also utilize variant functionality. By creating custom styles and assigning them a variant name, you can use the variant prop like so instead of specifying a className:

<Button variant="myCustomVariant">
  Button
</Button>

To create a custom variant, you can use the createTheme method. Refer to this answer for more information. Note that this feature is currently not supported in all components:

const theme = createTheme({
  components: {
    MuiButton: {
      variants: [
        {
          props: { variant: 'myCustomVariant' },
          style: {
            textTransform: 'none',
            border: `2px dashed grey${blue[500]}`,
          },
        },
      ],
    },
  },
});

Answer №2

In order to future-proof your code, I suggest using CSS Modules or Plain CSS over other styling solutions that may become deprecated soon. An example of this is the makeStyle method, which is now labeled as a Legacy styling solution.

Further details on this topic can be found on Mui's website under the Style library interoperability section.

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

Animate the appearance of list items sequentially using CSS animations

Is there a simpler way to achieve the effect of having list items slide in one after the other? The CSS method provided here seems quite intricate. #nav ul.is-visible{visibility:visible;opacity:1;-webkit-transform:scale(1);-ms-transform:scale(1);transfo ...

What exactly happens behind the scenes when utilizing the React hook useEffect()? Is an effect set up with useEffect able to halt the main thread

According to the documentation for the useEffect() hook in React, it states that: "Effects scheduled with useEffect don’t prevent the browser from updating the screen." Insight Unlike componentDidMount or componentDidUpdate, effects set with ...

Align dropdown navigation menu/sorting dropdown in the same position as the button

Exploring the world of dropdown menus in CSS has led me to encounter some challenges. I am striving to ensure that the dropdown boxes appear on the same line as the button that triggers them. Below is the CSS code I have been working with: /* global style ...

React Chart.js allows for consistent spacing for x-axes by displaying dates in a well-organized

After incorporating displayFormats in scales.x, I noticed that my xAxes labels are spaced differently based on the data object they contain. How can I adjust my xAxes labels to have equal spacing? The code snippet is displayed in the following image. Pleas ...

How to integrate SCSS into Next.js for enhanced styling capabilities?

editing the issue : __app instead of _app. I'm feeling a bit lost with my current problem. I'm trying to implement SCSS in my React/Next.js application but nothing seems to be working. I have installed the following packages: yarn add node-sas ...

Implementing Rate Limits in Next.js 14: A Guide on Programmatically Invoking React Server Actions

My application has a signup feature that requires users to input their email address, which is then added to the database using FormData. I am interested in simulating rate limiting using only the fetch API. Is there a way to achieve this without relying ...

I am looking for a way to display multiple images when the user clicks a button. It needs to be done

After successfully implementing a draggable single circle image when clicking a button, I am now looking to add multiple circle images each time the button is clicked. I'm considering using the append function with the canvas tag for this purpose. Ca ...

Issue with setting background image height to 100% or 100vh

Seeking help to address the issue of the URL field impacting the total height. Any assistance would be greatly appreciated. body,html { height:100% } Issue arises when there is a display in the address bar. .bg { min-height:100% background-size: cover; ...

Tips for breaking out of the foundation row and aligning with the right edge of the viewport

I have a CodePen example showcasing the Zurb Foundation grid. I am looking for a way to make a div extend to the right edge of the viewport while keeping the left edge in line with the grid as the viewport is resized. <div class="row"> <div cla ...

Stylish Radial Hover Effect for Images Using CSS

I am looking to create a unique effect where upon hovering over an image, color will be applied in a radial shape on a grayscaled image within a div that is pointed by the cursor Below you can see the desired outcome compared to what I currently have. The ...

Ways to retrieve the data from promises after they have been resolved?

I'm struggling to retrieve the values from getPeople(0,4). function getPeople(start, end) { const peopleArray = []; for (let i = start; i <= end; i++) { peopleArray.push( axios.get(`https://www.testsite.net/api/test/workers/ ...

I am struggling to increase the width of my input bar and center-align it

Below is the CSS class I've created to ensure that all elements remain centered on the user's screen. container: { display: "flex", position: "absolute", top: 0, left: 0, height: "100%&qu ...

Issue with Sliding Transition in React Material UI Drawer Component

I developed a custom drawer component for my React application const CustomSidebar = () => { return ( <Drawer open={drawerOpen} onClose={() => setDrawerOpen(false)} > <Box> <Navigator / ...

`Considering various factors to alter class pairings`

I have defined a few style classes in my stylesheet as shown below: .left-align{ /* some styles here */ } .right-align{ /* some styles here */ } .validate-error{ /* some styles here */ } Depending on the type of data, I need to align the content ei ...

The incorporation of zoom disrupts the smooth scrolling capability of the menu

My landing page has a menu that scrolls users to the selected section. However, my client prefers the page at a 90% zoom level. To accommodate this request, I added the following line of code: body { zoom:90%; } Unfortunately, when I click on a menu o ...

Encountering an Uncaught Error: Hydration issue as the initial UI does not match the server-rendered content

I am currently working on my main layout called rootLayout. However, I encountered some errors while creating the layout for my blog, which is BlogLayout. Can anyone provide me with a solution to fix these errors? ...

Rendering of @font-face on Windows 7 was executed flawlessly

I have been utilizing @font-face to implement custom fonts on a website. The custom font displays correctly in Firefox, IE, Safari, and Chrome on Mac. However, when viewed on Chrome in Windows 7, the text appears green at 10px instead of black or grey. ... ...

Manipulate classes based on scrolling (Wordpress)

Trying to manipulate a widget by adding and removing classes based on user scroll behavior has proven to be quite challenging. Specifically, I aim to add one class when the user scrolls down by 50px and remove it when they scroll back up. Website: Check o ...

Menu Selector on the Right Side

I am currently working on a drop down menu and trying to align it to the right using HTML and CSS. Below is an example that I have been referencing: http://codepen.io/anon/pen/RNLmvq Attached here is a screenshot of how the menu appears without the text ...

Dynamically update tab content in material UI

Within my React application page, I have a div with Material UI tabs. There are two tabs, one of which contains a list view also created with Material UI. I am looking to implement a behavior where clicking on a list item within the list view will result i ...