Adjust the color of the paper in Material-UI

I'm in the process of creating a React project using the material-ui library. Currently, I am facing an issue with customizing the drawer component's background color. After some research, I learned that modifying the paper attribute of the drawer should do the trick. Here is the code snippet I tried adding to my CSS object:

const styles = theme => ({
    background: "BLUE"

Subsequently, in my render function, I utilized the classNames library to reference this object:

render() {
    const { classes } = this.props;
    return (
        <div className={styles.root}>
            <CssBaseline />
            <Drawer 
                variant="permanent" 
                className={classNames(classes.drawer, {
                    [classes.drawerOpen]: this.state.open,
                    [classes.drawerClose]: !this.state.open
                })}
                classes={{
                    paper: classNames({
                        background: classes.background,
                        [classes.drawerOpen]: this.state.open,
                        [classes.drawerClose]: !this.state.open
                    })
                }}
            />
        </div>
    );
}

Despite all this setup, when I previewed it on localhost, the paper remained white and didn't reflect the desired blue color. Is there something specific about how classNames or the paper tag work that I might have overlooked? Any additional insights or guidance would be greatly appreciated. Thank you!

Answer №1

There are a few issues with the code snippet provided in your question.

To address the styling concerns, it is recommended to structure your styles as shown below:

const styles = theme => ({
    drawerPaper: { background: "blue" }
});

In this example, "drawerPaper" serves as the key for the class name, while the object on the right-hand side specifies the CSS properties associated with that class. When utilized within withStyles, this configuration will produce CSS similar to the following:

<style>
.classname-generated-for-drawerPaper-key: {
  background: blue;
}
</style>

The original issue stemmed from using a class name key of "background" with the value "BLUE" as the CSS property. Consequently, the resultant CSS would resemble the following:

<style>
.classname-generated-for-background-key: {
  0: B;
  1: L;
  2: U;
  3: E;
}
</style>

This format is invalid CSS and will not impact the visual appearance of the element.

The second problem pertains to how classes are defined:

    classes = {{
        paper: classNames({
            background:classes.background,
            [classes.drawerOpen]: this.state.open,
            [classes.drawerClose]: !this.state.open
        })
    }}

When passing an object to classNames, the keys represent class names, and the corresponding values determine whether each class should be included based on their truthiness or falseness. With the existing syntax, the inclusion of classes.background may inadvertently add a "background" class instead of the intended generated class name under classes.background.

A more suitable approach would look like this:

    classes = {{
        paper: classNames(classes.drawerPaper, {
            [classes.drawerOpen]: this.state.open,
            [classes.drawerClose]: !this.state.open
        })
    }}

This adjustment ensures the unconditional inclusion of classes.drawerPaper.

If you'd like to see an altered version of one of the Drawer demos with the drawer's background color changed to blue, feel free to explore the modified demo here: https://codesandbox.io/s/wqlwyk7p4l

Answer №2

To specify the color of a background paper when using global theme = createTheme(, you can set it as shown below:

const theme = createTheme({
   palette: {
   {
      primary: colors.blue,
      background: {
         default: colors.grey[50],
         paper: colors.common.white,
      },
      // ...

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

Deliver compressed data in gzip format from a Node.js server to the client using socket.io

I am currently facing an issue regarding determining whether the data being sent back to the client is compressed in gzip format or not. Upon examining my server's output from the command line, I notice the following: debug - websocket writing 3:::{" ...

Impressive javascript - extract file from formData and forward it

Presented here is my API handler code. // Retrieve data. const form = formidable({ multiples: true }); form.parse(request, async (err: any, fields: any, files: any) => { if (!drupal) { return response.status(500).send('Empty ...

Is there a way to initiate an AJAX post request with the Authorization header for the initial request using Windows Authentication?

I'm working on a web application that has a video page and a Web API for logging purposes. The events are triggered using an ajax post request: function logAction(actionToLog) { $.ajax({ type: 'POST', url: "/api/v/" + cu ...

What causes a double fill when assigning to a single cell in a 2-dimensional array in Javascript?

I stumbled upon this code snippet featured in a challenging Leetcode problem: function digArtifacts(n: number, artifacts: number[][], dig: number[][]): number { const land: boolean[][] = new Array(n).fill(new Array(n).fill(false)) console.log ...

Tips for grouping radio buttons that span multiple rows within an ag-grid

I am currently working on a grid layout that consists of multiple rows, with each row containing a radio button as illustrated in the snapshot below: https://i.sstatic.net/O8i0r.png Here is the code snippet for the column definition of the radio button: ...

Exploring the connection between Jquery and Javascript event handling within ASP.NET C# code-behind, utilizing resources such as books and

It seems that Jquery, Javascript, and AJAX are gaining popularity now. I am interested in learning how to use this functionality within C#. Do you have any recommendations for resources or books that teach JavaScript from a C# perspective on the web? Not ...

Utilizing Jquery for Enhancing Annotations

I am in the process of developing a website for essay writing tests. I have implemented a feature where users can input their essays using a text area, and now I want to be able to make comments on that text similar to PDF annotations or highlighting. I at ...

an online platform design

I am currently working on building a webpage, but I am facing some issues with the layout. Specifically, I am unable to make the div automatically adjust its size (particularly the height). Here is the code that demonstrates the problem: <!DOCTYPE html ...

What is the significance of h being undefined?

I have successfully set up a new Vue project using vue create and added Storybook with no issues. However, after installing storybook-addon-designs and following the instructions in the readme to add it to my story, I encountered an error in my console sa ...

Calculate the difference and sum of time values with varying signs in JavaScript

-12:00 - 5:30 => -6:30 -2:00 - 5:30 => 3:30 00:00 - 5:30 => -5:30 6:00 - 2:30 => 3:30 I am interested in subtracting time with both positive and negative indices. let myCountries = [ { countryName: "NewZealand", ...

Customizing Material UI themes: Step-by-step guide to altering the dropdown menu's background color

I am facing an issue with the theme settings below, specifically relating to the background color of the dropdown menu. I am trying to change the dropdown background to 'white', but it is currently showing the secondary theme color. Despite going ...

The act of sorting an item in jQuery triggers a reordering of items

I am working with a collection of items that represent different layers within div elements. One of my goals is to ensure that when I rearrange these items, their corresponding div layers are also sorted accordingly. Here is the list of sortable items: & ...

Creating unique styles with styled components without the use of selectors

Is it possible to achieve contextual styling without using CSS selectors? For example: <Button primary> <Text>BUTTON</Text> // if the button is primary then have 20px padding else 0 <Icon/> // if the button is primary then ...

Struggling to get custom CSS to apply properly in Joomla 4 with Bootstrap 5 template

Having created a simple Bootstrap 5 template for my Joomla 4 website, I've been attempting to customize the navbar with CSS in my user.css file. However, it seems that the styles added in user.css are not being applied. I have verified that user.css ...

Troubleshooting Flexbox in Internet Explorer 11: Issue with 100% width not functioning properly within nested flex containers with a 'column'

Is there a way to ensure that an image within nested flex containers has a width of 100% in IE11, even when the container has flex-direction: column? I've tried setting the width to 100% with a max-width of calc(100% - 0.1px), but unfortunately it doe ...

Structuring Server Side Code with Node.js and Express

I am faced with the task of restructuring my server and its components. My goal is to streamline the process by segregating different functionalities. app.post("/login", function(request, response) { }); app.post("/register", function(request, response) ...

Is it recommended to refactor class components to functional components once we migrate state management to Redux?

After delving into React and creating two class components with their own states, I delved into Redux and made the decision to migrate those states into the redux store. This leads to the question: "Would it be more beneficial to convert the class compon ...

Utilizing JSX interpolation for translation in React JS with i18next

I am trying to utilize a JSX object within the interpolation object of the i18next translate method. Here is an example code snippet along with its result: import React from "react"; import {useTranslation} from "react-i18next&qu ...

Obtain a Spotify Token and showcase information in next.js

This is a Simple Next.js component designed to display the currently playing song on Spotify. Context: Utilizing app Router Due to Spotify's token requirements necessitating a server-side call, the entire request is made to fetch the song from an ...

Achieve a safari-inspired checkbox appearance across all web browsers with custom CSS styling

In my asp.net mvc project, I am dealing with numerous checkboxes. The client has provided me with a PSD file in which the checkboxes are either white or black. In the absence of any check mark indicator, I assume the black ones are checked. My goal is to r ...