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

Is it possible to animate CSS Grid components?

Is it possible to animate a re-ordered set of elements in an array that are arranged using a CSS Grid layout? Check out this quick boilerplate ...

Using react hooks, I am refreshing the product image by replacing it with the thumbnail image

I'm currently working on an e-commerce platform that resembles Amazon. In the product detail page, I want the right side image to update when I click on a thumbnail image on the left side. The issue I'm facing is that upon first loading, the def ...

Update the Azure Variable group within the Azure Pipeline to include configurations for the .NET app settings and node JSON files

I have set up variable groups in the Azure library and linked them to an Azure pipeline. How can I initialize the xxx.json file? I also need to update the variables within the xxx.json file for both a React and .NET project. After adding variables to the ...

The primary tab's background color in a Shiny app

I had this question deleted previously while I was in the process of refining it. Is there a way to customize the background color of the active tab in a Shiny app? library(shiny) ui <- fluidPage( tags$head( tags$style(HTML(css)) ), tabsetP ...

What is the best way to connect individual buttons to a dynamic div that displays different content depending on the button clicked?

Hey there! I'm diving into the world of JavaScript and HTML, and I need some guidance on creating a menu that can toggle visibility of specific content in div(s) depending on which button (picture1-12) is clicked. My idea is to have one div that can d ...

Picture shown in the sidebar

I'm dealing with a table that has only one row containing text with new-line characters, such as: <td id='line-numbers'> <span class="number" id="1">1</span><br> <span class="number" id="2">123</span>< ...

The concept of localStorage is not recognized in the next.js framework

Currently working with next.js for frontend development. Facing an issue where I need to access user data from localStorage, but due to next.js being a server-side rendering framework, I am unable to retrieve data from localStorage. How can I solve this pr ...

I'm attempting to build a React app using the command (create-react-app app-name), however, I keep encountering an error. Can anyone shed some light on why this

Despite trying to clear the cache, my problem persists. It was functioning properly just a few hours ago, until I used npm run eject on another project. Since then, I have been encountering this error. I will include an error file along with the log. Can a ...

Creating a PHP Class for Converting CSS3 Rules to Ensure Compatibility Across Different Browsers

Seeking assistance with developing a class that can process a style sheet, identify browser-specific CSS3 rules, and provide compatibility for all browsers. The goal is to simplify the process of writing styles for one browser and then generating CSS files ...

What could be causing the lack of re-rendering in children components using redux-form?

When the parent component sends data, the children components do not re-render automatically. Re-rendering only occurs when a key is pressed on an input element. SMART User values from the state are sent by the smart component. If we add console.log(this. ...

Creating visually pleasing HTML emails with uniform table data heights

Struggling with Outlook while designing an HTML template. My row has 2 td elements with different content, and setting equal heights is proving to be a challenge. The fixed height on the td causes issues when switching to mobile view in Outlook as text wra ...

The image in the footer seems to have a mind of its own, refusing to stay put and instead choosing to wander

Is it possible to add a small icon at the bottom of the footer that scrolls up or down as I scroll, instead of remaining fixed? I'm unsure if the issue lies in setting the image as sticky on scroll or if it's a CSS error. I attempted to set the ...

Unable to properly cancel a post request using abort functionality

In the process of building a Next.js app, I encountered an issue with calling a post request. I included a cancel button to halt the post request, and attempted to use abortController in conjunction with Axios (v1.4.0) to achieve this. Even though the &ap ...

Detection of TextField blur event in Material UI

Is there a way to detect when the user leaves or focuses away from a field in Material UI TextField? I am looking for two events - one for entering and one for leaving the field. I know that we can use onFocus to handle entering the field, but is there an ...

Implementing a Dynamic Navigation Feature using PHP in a Standalone File

I am currently working on creating a dynamic PHP navigation system that should highlight the active tab, but I'm facing challenges with making the active tab part function properly. While there are simpler methods available, they all involve incorpora ...

Having trouble transferring file object from reactjs to nodejs

Hey there! I am relatively new to nodejs and React, and currently, I'm working on a project that involves sending a selected file from the front end (React) to the back end (Node). The goal is to upload the file and convert it into a JSON object. Howe ...

Issue with attribute not being saved in MongoDB (MERN stack)

I am currently developing an app that evaluates students' algebra 1 proficiency. I have been facing an issue where I am trying to send a string named "answers" to the database, but for some reason it is not getting submitted. The model/schema I have s ...

Having trouble incorporating a title in the header section

I encountered an issue while attempting to include the Fragment, title, and Head. When these are added, an error occurs but when removed, the page displays correctly. I have searched for a solution to this problem but couldn't find anything. import ...

Typescript error points out that the property is not present on the specified type

Note! The issue has been somewhat resolved by using "theme: any" in the code below, but I am seeking a more effective solution. My front-end setup consists of React (v17.0.2) with material-ui (v5.0.0), and I keep encountering this error: The 'palet ...

How can I align the tags properly when inserting a tab box within a section tag?

How can I successfully insert a tab box within my section tag? I found this tab box tutorial on the website here The download link for the source code is available here: source code Below is the HTML code snippet: <!DOCTYPE html> <html> & ...