简体   繁体   中英

Changing the Color of the Drawer in Material-UI React

I want to change the background color of my MUI drawer. Here is my header code:

import { AppBar, Toolbar, Typography, makeStyles, Button, IconButton, Drawer, Link, MenuItem } from "@material-ui/core";
import React, { useEffect, useState } from "react";
import { Link as RouterLink } from "react-router-dom";
import MenuIcon from "@material-ui/icons/Menu";
import logo from "./Icon.png";

const useStyles = makeStyles (() => ({
    header: {
        backgroundColor: "#1b1b1b",
        paddingRight: "0px",
        paddingLeft: "18px",
        "@media (max-width: 900px)": {
            paddingLeft: 0,
        },
    },
    menuButton: {
        fontFamily: "Inter, sans-serif",
        fontWeight: 700,
        size: "18px",
        marginLeft: "38px",
    },
    toolbar: {
        display: "flex",
        justifyContent: "space-between",
    },
    drawerContainer: {
        padding: "20px 30px",
        color: "inherit",
    },
}));

const headersData = [
    {
        label: "Featured",
        href: "/featured",
    },
    {
        label: "Favorites",
        href: "/favorites",
    },
    {
        label: "My Account",
        href: "/account",
    },
    {
        label: "Discord",
        href: "/discord",
    }
];

export default function Header() {
    const [state, setState] = useState({
        mobileView: false,
        drawerOpen: false
    });

    const { mobileView, drawerOpen } = state;

    useEffect(() => {
        const setResponsivness = () => {
            return window.innerWidth < 900
            ? setState((prevState) => ({ ...prevState, mobileView: true }))
            : setState((prevState) => ({ ...prevState, mobileView: false, drawerOpen: false }));
        };

        setResponsivness();
        window.addEventListener("resize", () => setResponsivness());

        return () => {
            window.removeEventListener("resize", () => setResponsivness());
        }
    }, []);

    const { header, menuButton, toolbar, drawerContainer } = useStyles();
    const displayDesktop = () => {
        return (
            <Toolbar className={toolbar}>
                <a href="/">{smomodsLogo}</a>
                <div>{getMenuButtons()}</div>
            </Toolbar>
        )
    };

    const getDrawerChoices = () => {
        return headersData.map(({ label, href }) => {
            return (
                <Link
                    {...{
                        component: RouterLink,
                        to: href,
                        color: "inherit",
                        style: { textDecoration: "none" },
                        key: label,
                    }}
                >
                    <MenuItem>{label}</MenuItem>
                </Link>
            )
        })
    }

    const displayMobile = () => {
        const handleDrawerOpen = () =>
            setState((prevState) => ({ ...prevState, drawerOpen: true }));
        const handleDrawerClose = () =>
            setState((prevState) => ({ ...prevState, drawerOpen: false }));
        return (
            <Toolbar>
                <IconButton
                    {...{
                        edge: "start",
                        color: "inherit",
                        "aria-label": "menu",
                        "aria-haspopup": "true",
                        onClick: handleDrawerOpen,
                    }}
                >
                    <MenuIcon/>
                </IconButton>
                <Drawer
                    {...{
                        anchor: "left",
                        open: drawerOpen,
                        onClose: handleDrawerClose,
                    }}
                >
                    <div className={drawerContainer}>{getDrawerChoices()}</div>
                </Drawer>
                <div><a href="/">{smomodsLogo}</a></div>
            </Toolbar>
        )
    }

    const smomodsLogo = (
        <Typography variant="h6" component="h1">
            <img src={logo} alt="SMOMods" width={224} height={70}/>
        </Typography>
    )

    const getMenuButtons = () => {
        return headersData.map(({ label, href }) => {
            return (
                <Button
                    {...{
                        key: label,
                        color: "inherit",
                        to: href,
                        component: RouterLink,
                        className: menuButton
                    }}
                >
                    {label}
                </Button>
            );
        });
    };

    return (
        <header>
            <AppBar className={header}>{mobileView ? displayMobile() : displayDesktop()}</AppBar>
        </header>
    );
}

The drawer uses Material-UI in ReactJS. I am really new to React and it's my first time using it. I have added something like BackgroundColor: "#1b1b1b" to the code before but it only changed the background color behind the buttons and not the full drawer!

There is documentation written under the Drawer tab.

https://mui.com/api/drawer/

There is another way to do that is to overwrite the original class by inspecting that element, or create an above your drawer, and change the color as a child.

I forked your example and apply the changes from the question that I suggested you via comments before and here you have your code working with a red background for the Drawer.

Changes I introduced to make it work were all in the Header.js file:

  • Added new style named paper to the makeStyles invocation at line 17
  • Changed const { header, menuButton, toolbar, drawerContainer } = useStyles(); by const { paper, header, menuButton, toolbar, drawerContainer } = useStyles();
  • Added classes={{ paper }} to the Drawer instance

A few extra things you could improve:

You do not need destructuring when you use a component:

        <Drawer
          classes={{ paper }}
          {...{
            anchor: "left",
            open: drawerOpen,
            onClose: handleDrawerClose
          }}
        >
          <div className={drawerContainer}>{getDrawerChoices()}</div>
        </Drawer>

Is usually written like this:

        <Drawer
          classes={{ paper }}
          anchor="left"
          open={drawerOpen}
          onClose={handleDrawerClose}
        >
          <div className={drawerContainer}>{getDrawerChoices()}</div>
        </Drawer>

Instead of:

  return (
    <header>
      <AppBar className={header}>
        {mobileView ? displayMobile() : displayDesktop()}
      </AppBar>
    </header>
  );

You should do:

  return (
    <AppBar className={header}>
      {mobileView ? displayMobile() : displayDesktop()}
    </AppBar>
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM