Replacing Material-UI with SCSS

In my current React project, I am utilizing MUI and Sass. The issue I am facing is that there are numerous scss files filled with !important declarations to override the MUI styles using Sass. To address this issue, I attempted to eliminate the !important declarations and incorporate the following code snippet:

import { StyledEngineProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline'

<CssBaseline />
<StyledEngineProvider injectFirst>
*** component tree here ***
</StyledEngineProvider>

This approach initially appeared to be working fine, but it ceases to work properly when focusing on a specific component. For instance, a button turns white with a blue border upon hovering over it:

scss

.button {
    width: 250px;
    height: 50px;
    border: 1px solid grey;
    border-radius: 15px;
    text-transform: none;
}

.go-button {
    @extend .button;
    background-color: grey;
    color: whitesmoke;
}

reactjs

<Button
   className="go-button"
   variant="outlined"
   onClick={handleClick}
>
   Go
</Button>

We are not making use of modules or makeStyles. What would be the most effective approach to overriding MUIS styles without relying on !important declarations?

Answer №1

When customizing the styles of MUI components, it's important to consider the specificity of certain states like :hover, .Mui-focused. These states have a higher specificity than the default styles, so when overriding them, you need to match that same specificity level.

For example, the Button component has default hover styles that can be overridden by specifying new styles for the hover state.

To define custom button styles, you can use the following approach:

.button {
  width: 250px;
  height: 50px;
  border: 1px solid grey;
  border-radius: 15px;
  text-transform: none;
}

.go-button {
  @extend .button;
  background-color: grey;
  color: whitesmoke;
}
.go-button:hover {
  @extend .go-button;
  background-color: #999;
}

https://codesandbox.io/s/scss-button-styles-rz4o8i?fontsize=14&hidenavigation=1&theme=dark

Answer №2

In my experience, using styled-components with MUI is the way to go. They are a better match compared to SCSS, resulting in improved website performance. With styled-components, making changes to MUI is easy and seamless.

For more advanced usage tips, check out this link

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

Encountering a Typescript error when attempting to access the 'submitter' property on type 'Event' in order to retrieve a value in a |REACT| application

I am facing an issue with my React form that contains two submit buttons which need to hit different endpoints using Axios. When I attempt to retrieve the value of the form submitter (to determine which endpoint to target), I encounter an error while work ...

Express.js Server Side Rendering - GET request for '/json/version/'

I have a running express server that pre-renders my react application. The routes file matches the HomeContainer to the base route / and all other routes match to the page not found. import HomeContainer from 'containers/home-container/home-container ...

Leveraging the power of useContext alongside useRef and useState

I recently created a function in the last code snippet that hides the input search when the user clicks anywhere outside of it. Now, my goal is to have the input cleared out when it hides. I attempted various approaches such as using useState and passing ...

Methods to validate CSS attributes specified within a class using React testing library

I am struggling to validate the CSS properties defined within a class in CSS using the React Testing Library. Unfortunately, I am facing challenges in doing so. Here are the simplified code snippets: import React from "react"; import { render, ...

The CSS styles are failing to load properly for the antd Menu option

I am working with React using the Next.js framework, and I've integrated the antd npm package for components like tables and menus. However, I'm facing an issue where the CSS is not loading for these controls. What could be causing this problem? ...

Assist with automatically updating a field value based on user input during React Hook Form validation

TL;DR To see the working code, visit: https://codesandbox.io/s/stoic-beaver-ucydi The refactored version using React Hook Form can be found here: https://codesandbox.io/s/objective-cloud-bkunr?file=/src/ControlledTextField.tsx In Depth Explanation No Re ...

Unable to modify array state with data from another state

Two state objects are at play here. The first is personnel, which consists of an array of 1-object arrays structured like this: [[{}],[{}],[{}],[{}],...]. The second state object is rowItems, where the goal is to extract all objects from the inner arrays o ...

Creating Multiple Result Lists in MUI Autocomplete Based on Option Properties: A Step-by-Step Guide

I have a query about displaying results using the MUI Autocomplete component. I am looking to categorize the results into two separate lists placed side by side. Currently, I have a working searchbar with one list of results. However, I aim to segregate t ...

"Encountered an issue with Next-Auth session returning as undefined in getServerSideProps using NextJS version 13.2

When inspecting the code below, session is found to be undefined upon logging from the client side after being transferred from getServerSideProps. import { getServerSession } from 'next-auth/next'; import { authOptions } from './api/auth/[. ...

Submitting multiple values in React-PDF

I've been working on a form that allows users to input their name and surname, and then generate a pdf document from the entered information. To achieve this, I'm utilizing . However, I've encountered an issue where I can only submit one va ...

Is it possible in ReactJS to return JSX from a callback function?

After spending some time working with react, I encountered a basic issue that has me stumped. In the Login component, I am submitting a form and if it returns an error, I want to render a snackbar message. handleSubmit = (event) => { event.preven ...

React-snap causing trouble with Firebase

I'm having trouble loading items from firebase on my homepage and I keep running into an error. Does anyone have any advice on how to fix this? I've been following the instructions on https://github.com/stereobooster/react-snap and here is how ...

Images on NextJS are failing to resize properly in Next 13

I have been facing challenges with optimizing image sizes for different screen resolutions using the NextJS Image component. Currently, all images seem to be loading at their largest size on various screens. Below is a screenshot showing the resolution t ...

Having issues with unchecking checkboxes in ReactJS

I created a task management app and I thought of improving it by displaying all completed tasks when the "Show completed tasks" box is checked. https://i.stack.imgur.com/RkXsw.png The issue I'm facing is that while checking "Show completed tasks ...

What is the best practice for storing references to DOM elements in Reactjs?

class SearchInput extends React.Component { constructor(props) { super(props); this.searchInputRef = React.createRef(); // ...

Using JavaScript, import the variable module object from a specific module

Is there a way to import a module object from a module if I am unsure of the specific objects I will need beforehand? How can I utilize a variable in place of fixed module names? import { dynamicVariable } from './module' The variable represents ...

Guide on transforming headless wordpress href to a <Link> tag

I am currently working on a project using Next.js with the WordPress API, also known as headless WordPress. In my application, I am displaying content from a Gutenberg area which includes text and links. However, a problem I have encountered is that the li ...

The 'import.meta' meta-property can only be used with the '--module' set to 'es2020', 'esnext', or 'system'.ts(1343)

Whenever I attempt to utilize import.meta.url (as demonstrated in the Parcel docs), I am consistently met with the error message "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es ...

In an unforeseen twist, an unconventional token has surfaced within the componentDidMount

I am attempting to utilize the componentDidMount method and export it as a default, but I keep encountering an error. It says "Unexpected token, expected ','". The code works fine when I use the export default class HelpScreen extends React.Compo ...

Leverage information from graphql API response to enhance functionality in React components

Hey there, I'm facing a little challenge that's been keeping me stuck for a while now, so any advice or guidance would be greatly appreciated! Currently working on a react app where I'm making a call to a GraphQL api using apollo. Within an ...