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

Prevent duplicate items in an array by utilizing the Map object to add elements

Looking for a way to update an array by adding new values while avoiding duplicates. I've implemented the usage of a Map object to keep track of existing values and tried filtering the new array accordingly. const [items, setItems] = useState([]); ...

What is the best way to align the items in two lists at the center as if they were all individual

Q: How can I center the list-item elements of two unordered lists as if they were children of just one list? Example: {[1][1][1][1][2][2]} { [2][2] } CSS Alignment Challenge <div> <ul> &l ...

Utilize SVGs efficiently by loading them once and reusing them

Is it possible to use the same SVG element twice on a web page without having to load it again? I am changing the CSS of the SVG using JavaScript, so I believe the SVG must be directly embedded in the HTML rather than included as an object. Both instance ...

Stopping the <nav> element from displaying as "unlabeled section" on HTML5 webpages

As I work on incorporating proper sectioning in HTML5 with sectioning elements and headlines to meet my customer's design goals (while adhering to certain restrictions), I have encountered a challenge. The basic layout requested is as follows: <b ...

Utilize React Searchbar to navigate to a new page and incorporate a component into the process

I am working on a search bar functionality where upon submission, I need to redirect the user to another page while passing the input value along with them, preferably as a prop. <AsyncSearch filter options={items} onSubmit={(inputValue) => ...

Implement CSS to stack images upon zooming

On my menu page, I have two images that I want to display side by side in the web browser and stacked on top of each other in a column when viewed on mobile. Currently, with framework7's row and column classes, the images are positioned next to each o ...

Persistent error caused by unresponsive Tailwind utility functions

Currently, I am working on a Next.js application and encountered a strange error while adjusting the styling. The error message points to a module that seems to be missing... User Import trace for requested module: ./src/app/globals.css GET /portraits 500 ...

Troubleshooting Navigation Bar Toggle Button Issue in Bootstrap 5

Currently, I am in the process of working on a web project that requires the implementation of a responsive sidebar. This sidebar should be toggleable using a button located in the navigation bar. My choice for the layout is Bootstrap, and I have come acr ...

Strategies for identifying CSS properties within a div element

I am attempting to identify the CSS property display of a div. If it is set to display:block, I want to change the icon to -. If it is set to display:none, I want to change the icon to +. I have tried using the following code but it does not seem to work: ...

What is the best way to split a Bootstrap navbar into two separate rows?

I'm struggling with breaking the navbar to have the navbar-brand in one row and the collapse menu in another. <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="72101d1d0601060013 ...

Utilizing a jQuery plugin for input file validation

This code is functioning properly, however the file field is not being validated. All input fields are successfully validated by this plugin except for the file type field. I believe there may be something missing in my implementation, so please help me de ...

Add the unique identifiers of objects to an array when a checkbox is selected within a React.js Functional Component

I am working with an array where I need to add the object IDs when a checkbox is checked, and remove the IDs when the check mark is removed by an admin. <Form.Label>Select Package/s:</Form.Label> {packages.map((item) => ( <Form.Check ...

JavaScript code to read a .txt file

Is it possible to use JavaScript to read a text file directly with the file path provided in the code, rather than selecting the file from an open file window? ...

Using React Hook Form with Material UI Slider

I'm facing difficulties in integrating the Material UI Slider with React Hook Form. The values are not being registered and when I check the console.log, it displays undefined. Any thoughts on where I might have gone wrong? <Controller re ...

Next.JS is efficiently compressing images into base64 format, resulting in an empty image

I recently uploaded a pizza.jpg image to Cloudflare Pages and embedded it into a (.jsp file) page. <div className="product_img"> <Image src={'pizza.jpg'} loader={localLoader} alt={'Pizza'} width='300' he ...

Ensure that the dimensions of a div remain consistent across all screen resolutions, specifically for desktops and not mobile devices

Currently I am in the process of creating a highly secure and encrypted social network, but I have hit a stumbling block. I hadn't considered how my website would display on other desktops and laptops (not mobile devices). The issue is that I set all ...

Building a web application using Django REST framework and React JS, and utilizing Axios to post JSON data with an image file included

Is there a way to upload image files to the Django_Rest framework using axios? I have a basic model: class Article(models.Model): title = models.CharField(max_length=120) text = models.TextField() img = models.ImageField(upload_to='articl ...

Ways to incorporate hover transition duration for a button in Chakra UI

I'm having trouble adding a transition duration on hover for a button. <Button bgGradient='linear(to-r, #003e9b, #5949b4, #ad53cc 80%)' color='white' _hover={{bg:'linear-gradient(to left,#003e9b ,#5949b4 ,# ...

Discovering an <a> element with an href attribute containing two specified strings

Here's what I have: $("a[href*='string1' && 'string2']") Unfortunately, this code didn't work for me. I also attempted: $("a:contains('string1' && 'string2')") The second one only return ...

Include a new element immediately after the user begins typing in the input field

Recently, I figured out how to dynamically add an item based on the state. As the user types something in the input field, it generates list items based on the state mapping. Here's a sample code snippet: return ( <div className="App&qu ...