Unlock the power of Material UI styling using hooks for easy customization

My goal is to create an AppBar that is clipped to the top of the page and hovers over another Drawer using React Hooks and Material Ui by applying a class name. I followed the example provided at: https://material-ui.com/demos/drawers/#clipped-under-the-app-bar

Here is the code snippet:

const useStyles = makeStyles(theme => ({
root: {
    display: 'flex',
    height: '100%',
},
drawer: {
    width: drawerWidth,
    flexShrink: 0,
},
appBar: {
   zIndex: theme.zIndex.drawer + 1,
},
menuButton: {
    marginRight: 20,
    [theme.breakpoints.up('md')]: {
        display: 'none',
    },
},

}));

And the render function:

     <div className={classes.root}>
                <CssBaseline/>
                <LoadingResults showLoading={showLoadingSpinner}/>
                <AppBar position="fixed" className={classes.appBar} >
                     ...
                </AppBar>
    ....

The issue I am facing is that when the style is applied with the class name, it is added as the last element which prevents it from overriding the original style:

class="MuiPaper-root-12 MuiPaper-elevation4-18 MuiAppBar-root-3 MuiAppBar-positionFixed-4 MuiAppBar-colorPrimary-10 mui-fixed Hook-appBar-1b6f20g"

I am aware that inline styles can be used but I am curious if there is a way to override styles using class names with hooks similar to the "legacy" component approach?

Here is the sandbox for reference: https://codesandbox.io/s/w7njqorzy7?fontsize=14

In the sandbox environment, the code works fine (AppBar over the lefthand side container): https://i.sstatic.net/0HmFu.png

However, when the same project is downloaded and compiled, the layout is not correct: https://i.sstatic.net/vQdkv.png

Upon inspecting the debugger, I noticed that the styles are inline. In the sandbox, hooks appear at the bottom:

https://i.sstatic.net/wBweo.png

But in the browser, when the app is run via "run start," they appear on top:

https://i.sstatic.net/TXy7h.png

This seems to be the root cause of the difference in behavior between the two environments. However, I am unsure why this happens and how to resolve it.

Answer №1

It was discovered that the location of my bootstrap.js file with updated styles was incorrect.

import { install } from '@material-ui/styles';

install();

This should be run before importing any material ui component.

Answer №2

Visit this link for more information on advanced styles in Material-UI

const customStyles = makeStyles({
  main: {}, // customized style
  title: {}, // embedded style
});

function EmbeddedComponent(props) {
  const classes = customStyles(props);
  return (
    <button className={classes.main}>
      <span className={classes.title}> // 'jss2 my-title'
        embedded
      </span>
    </button>
  );
}

function MainComponent() {
  return <EmbeddedComponent classes={{ title: 'my-title' }} />
}

Answer №3

To customize material-ui styles, use the classes prop instead of classNames.

For instance:

<AppBar position="fixed" classes={{root: classes.appBar}}>

In this example, I utilized the root key for customization, but there are several other keys you can experiment with.

Each Material-ui component has an api section where you can find a list of keys available for customization.

Helpful resources:

Customization Documentation

App Bar API Reference

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

Easy way to eliminate empty elements following a class using jQuery

I'm encountering a situation where I have a group of elements following a specific class that are either empty or contain only white space. <div class="post-content"> <div class="slider-1-smart"> --- slider contents --- < ...

Tips for CSS: Preventing onhover animation from resetting with each hover

I've created an on-hover CSS animation that smoothly transitions between images. However, I encountered a lagging issue when the user quickly hovers over SECTION ONE and SECTION TWO before the animation ends, causing the animation to restart and lag. ...

Leveraging random attributes in Next.js without encountering the "server/client mismatch" issue

Is there a way to generate unique IDs for form inputs dynamically, in order to avoid conflicts with other elements that share the same ID? If multiple login forms are present on a single page, each with an 'email' field, setting the id property b ...

Using an Array as a prop in a React component: A step-by-step guide

Currently, I am in the process of learning React by building a website to gain more familiarity with it. As part of my project, I have been experimenting with the "use-dencrypt-effect" npm package. However, I encountered an issue where setting its values v ...

Issue with React and Mongoose: State Change Not Being Saved

I am facing an issue with changing the state of my checkbox. Initially, the default option in my Mongoose model is set to false. When a user checks the box and submits for the first time, it successfully updates their profile (changing the value to true). ...

React.js Filter Component

I'm currently trying to create a filter for my "localtypes", but I'm encountering an issue where the console in my browser is displaying an empty array. My goal is to access the localtypes properties of the API that I am working with. I attempte ...

I am experiencing an issue with Safari where there is an unexpected rounded border appearing that

Upon inspecting the image, a slight border is visible behind the main border on Chrome and Firefox. However, Safari and iPhone display a rounded thin border instead. Can you help us understand why this discrepancy is happening and how we can remove it? P ...

Display the MaterialUi snackbar using a specific process

I'm interested in displaying a message using material.ui by only calling a method and not adding a component to the parent component (similar to toastify.js). I tried an example like the one below, but I'm having trouble calling the showSnack() m ...

The NodeJS server encountered an issue while trying to load the XMLHttpRequest from the localhost. The specified link type of

When accessing the same link to a jsx file (containing ReactJS code) online, everything works fine. However, when attempting to open it on NodeJS localhost, an error occurs: "XMLHttpRequest cannot load http://.../js/r1BodyBabel.js. No 'Access-Contro ...

What is the best way to pass a list between two components in React?

App.jsx module: import React from 'react'; import './App.css'; import {Route,Switch} from 'react-router-dom'; import Conduct from './extras/conduct'; import Vote from './extras/vote'; import Menu from &apos ...

Grid layout with columns of equal width in Bootstrap

I'm currently working on creating a dashboard with Angular and Bootstrap 4. I've utilized the equal-width columns from https://getbootstrap.com/docs/4.0/layout/grid and it's functioning well. However, I'm facing an issue where if the lo ...

"How to retrieve the height of an element within a flexslider component

I need some assistance with using JavaScript to determine the height of an element within a flexslider. There are two challenges I am facing. When I attempt to use a regular function getHeight(){ var h = document.getElementById("id-height").style.height; ...

Change the quality of a React component by reacting to an event

I am currently working on a React Element that contains nested elements. I need to update the idtest attribute of one of these elements dynamically. Here is how I have declared this element: const [currentTest, setCurrentTest] = useState(<PsqMainPan ...

Fine-tuning CSS layout based on perspective alteration

I am working with the following code: function exportTableToExcel(tableID, filename = ''){ var downloadLink; var dataType = 'application/vnd.ms-excel'; var tableSelect = document.getElementById(tableID); var tableHT ...

How do I customize the border color for the Select component in Material UI?

I have been working on customizing the Select component provided by Material UI. Here is a visual representation of what it currently looks like: https://i.stack.imgur.com/YGheB.png My goal is to change the border-color of the select component from the ...

A guide on customizing input element styles in a React application

I need assistance with customizing the appearance of an input component based on user input. For instance, I want to modify the background color if the entered value is less than the current year. Here is the function that checks the validity of the enter ...

Creating personalized Stop and Play controls for Swiper.js Autoplay feature in a React/Next project

My quest to create a Swiper in React with autoplay functionality using Swiper.js has been quite a challenge. Despite following the instructions diligently and researching extensively, I couldn't find a solution. I even tried referencing a jQuery examp ...

Ways to change CSS using the * / all notation

After downloading a scrolling image plugin from the internet, I encountered an issue while trying to implement a left-floating Social Media bar. The CSS for the media bar conflicts with the scrolling plugin's CSS and as a result, the social media bar ...

What is the best way to vertically center a row?

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Unique Title</title> <link rel="stylesheet" href="custom-reboot.min.css"> <link rel="stylesheet" href="custom-style.min.css"&g ...

Fix for JqGrid Height Issue Not Functioning as Expected

The implementation of jqgrid on my webpage has a fixed height requirement, where users should be able to scroll down if there are more rows. While this works well for tables with many rows, I am facing an issue with tables that have fewer rows. In these ca ...