Exploring Material UI: Step-by-step guide to customizing component styles

After reviewing the documentation, I have discovered two ways to style the component:

import * as React from 'react';
import { makeStyles } from '@mui/styles';
import Button from '@mui/material/Button';

const useStyles = makeStyles({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});

export default function Hook() {
  const classes = useStyles();
  return <Button className={classes.root}>Hook</Button>;
}

Alternatively, you can style it like this:

import * as React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@mui/styles';
import Button from '@mui/material/Button';

const styles = {
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
};

function HigherOrderComponent(props) {
  const { classes } = props;
  return <Button className={classes.root}>Higher-order component</Button>;
}

HigherOrderComponent.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(HigherOrderComponent);

I've been attempting to modify the style when a specific event occurs, such as switching to dark mode:

const manageDarkModeUpdateWhenUserTogglesIt = () => {
  window.addEventListener("storage", () => {
    // This event is triggered when the user enables dark mode
    // I need to update the style here
  });
};

I am struggling to find a solution to update the style using either of the mentioned methods, and any changes I make result in errors. Can anyone provide assistance?

Answer №1

Utilize the theming feature of MUI to customize light and dark modes according to your preferred styles. You can access these styles inside the makeStyles function:

const getTheme = (mode) => {
  return mode === 'light'
    ? //regular style
      {
        root: {
          background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
          border: 0,
          borderRadius: 3,
          boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
          color: 'white',
          height: 48,
          padding: '0 30px',
        },
      }
    : //dark mode style
      {
        root: {
          //your style
        },
      };
};

App.js

const App = () => {
    //Add state mode here
    const [mode, setMode] = useState("light")
    const theme =  createTheme(getTheme(mode));

    return <ThemeProvider theme={theme}>...</ThemeProvider>;;
}

Your component

import * as React from 'react';
import { makeStyles } from '@mui/styles';
import Button from '@mui/material/Button';

const useStyles = makeStyles((theme) => ({
    root:theme.root,
  }));

export default function Hook() {
  const classes = useStyles();
  return <Button className={classes.root}>Hook</Button>;;
}

Another point to note is that makeStyles might be considered outdated.

Answer №2

To resolve this issue, I utilized the concept of "Dynamic styling" found in the Material-UI customization guide:

import Tabs from "@material-ui/core/Tabs";
import { styled } from "@material-ui/core/styles";

const CustomTabs = styled(Tabs)({
  flexGrow: 1,
  width: "100%",
  backgroundColor: "var(--background-color)",
});

const darkModeVars = {
  "--background-color": "#16213E",
};

const defaultModeVars = {
  "--background-color": "#ffffff",
};

function EnhancedTabComponent(props) {
  const [vars, setVars] = React.useState(
    localStorage.darkMode == "true" ? darkModeVars : defaultModeVars
  );

  useEffect(() => {
    handleDarkModeToggle();
  }, []);

  const manageDarkModeUpdateWhenUserTogglesIt = () => {
    window.addEventListen("storage", () => {
      if (localStorage.darkMode == "true") {
        setVars(darkModeVars);
      } else {
        setVas(defaultModeVars);
      }
    });
  };
  
  return (
    <div>
      <AppBar position="static" color="default">
        <CustomTabs style={vars}></CustomTabs>
      </AppBar>
    </div>
  );
}

export default withRouter(EnhancedTabComponent);

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

Utilizing styled() to apply custom Material UI style overrides directly to individual components

Seeking a way to isolate styleOverrides for a specific component using styled() instead of cluttering my global theme file with numerous overrides, as seen in Material UI's documentation on How to Customize. My current theme setup involves customizin ...

Implementing loading animation upon button click in Reactjs

I am facing a situation where I need to update the vote counts of three election contestants by making Axios calls to the server backend. So far, everything is working smoothly and I am able to receive JSON responses from the Axios calls. [{ "id": "1", " ...

Material Design Forms in Angular: A Winning Combination

I'm currently working on developing a form using Angular Material. This form allows the user to update their personal information through input fields. I am utilizing "mat-form-field" components for this purpose. However, there are certain fields tha ...

Use the arrow key to move through the different layers

I'm working on enhancing a custom auto-complete feature using JQuery. My goal is to allow the user to navigate down into the auto-complete dropdown and then back up to the input box that triggered it initially. The code snippet below demonstrates how ...

the secret to accessing the most recent state value post-update within a function

My current issue involves retrieving login user details and updating the state with that data for further processing. Unfortunately, it takes around 2-3 seconds to update the state and make use of the information. To address this delay, I have found a sol ...

What is the best way to display a confirmation dialog when a user interacts with a button in a ReactJS application?

In my React application, I have multiple buttons that need to display a confirmation message when clicked. Depending on the button, I would like to show different messages such as "Are you sure you want to delete the user?" or "Are you sure you want to d ...

List the acceptable favicon formats for Internet Explorer version 10 and above

When I say type, I'm referring to the file extension. My favicon displays correctly in Firefox, Chrome, and Safari, but someone suggested that the issue may be related to the favicon type. Is there a reliable online resource where I can find informa ...

Basic Search tool, displaying a <div>

Hey there, I've been searching for a solution for a while now and haven't found one yet. So here's my question: I created a simple website to display random recipes for those times when you're not sure what to make for dinner. I also w ...

Troubles with Borders and Padding in HTML Elements

Hello everyone, I'm currently facing an issue trying to neatly fit a textbox, select menu, and button all within the same sized div. Each element seems to have strange borders/margins causing them not to display properly (the button ends up below the ...

Is there a way to bypass the user-select: none property for the labels in RadioButton and CheckBox controls?

Currently, for versions before 1.0.0 of Material-UI, text selection is disabled on RadioButton and Checkbox control labels. Is there a way to override this behavior? It seems that passing labelStyle={{ userSelect: 'all' }} to the component does ...

React-Router DOM failing to display the content from additional pages

// App.js import React from 'react'; import Contact from './Contact'; import About from './About'; import Nav from './Nav'; import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'; function ...

Styling using CSS is effective only when applied locally, as it does not function properly on GitHub Pages

Although I have come across similar questions to the one I am facing, none of the solutions provided seem to work for me at the moment. My CSS file loads and functions as expected when tested locally, but once I upload it to GitHub, it stops working. In my ...

Is the state of the React.js component empty?

HTML: <!-- index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>React Tutorial</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script> ...

The Bootstrap 4 column is not floating properly to the right as it is leaving a gap on the

My right sidebar is not floating to the right and has space from the right side. You can view it at this link: <div class="col-md-2 col-lg-2 col-sm-2" id="right-sidebar" style="background-color:orange; float: right; right: 0!important; width: 100%;"& ...

Using drawer navigation to pass data/parameters in React Navigation 5

I am facing an issue with passing parameters between two screen components that belong to different navigators. First, I have the Login component inside a Stack navigator, and then I have the Home component inside a Drawer navigator. The hierarchy is as f ...

How to ensure two unordered lists are aligned at the same baseline using CSS

Is it possible to align two UL's to a single baseline, with one UL aligned flush left and the other flush right? Currently, the UL's are not aligned and appear like this: How can I make sure the two UL's share the same baseline? CSS #foo ...

Tips for effectively wrapping Material UI v5 component to ensure the Grow component functions correctly

Being a newcomer to React, I want to apologize in advance for any silly mistakes or inaccuracies that may be present. I have successfully implemented the code for my Blog page: export default function Blog() { const [photos, setPhotos] = useState([]); ...

Issue with Brave browser: CSS animations not functioning properly, although they work perfectly in Firefox

Link to Codepen: https://codepen.io/sabeser/pen/RwYzJpd HTML: <div id='wrapper'> <div class='circle'></div> <div class='circle'></div> </div> CSS: :root { --scale--rati ...

The MUI makeStyles() class has been implemented, yet the styles are not being displayed when using classList.add('class-name')

Currently, I am utilizing MUI makeStyles() to create a series of CSS classes. Within these classes, I am dynamically including and excluding one specific class to my Box element during file drag-and-drop events. The class is successfully added, as I can o ...

extracting both the value and ID attributes from a RadioButtonGroup component in React MaterialUI

I am currently working on extracting the selected value and gameID from a dynamic MaterialUI RadioButtonGroup. Although I have been successful in retrieving the gameID, I am encountering difficulty in obtaining the value: <form onSubmit={this.handl ...