What is the best way to utilize the sx prop in Material UI for applying styles specifically when the component is active or selected?

In the code snippet below, I have set up the useState hook so that when a ListItem is clicked on, the selected state becomes true. My goal is to apply specific styling when an item is selected using the sx prop instead of creating a styled component for such simple styling requirements. What I want to achieve is to change the color of the ListItemText to blue and the background color of the ListItem to a lighter shade of blue when it is selected.

import { useState } from 'react'
import { Box, Drawer, CssBaseline, AppBar, Toolbar, Avatar, List } from '@mui/material';
import Typography from '@mui/material/Typography';
import ListItem from '@mui/material/ListItem';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import HomeOutlinedIcon from "@mui/icons-material/HomeOutlined"
import PeopleOutlinedIcon from "@mui/icons-material/PeopleOutlined"
import PersonOutlinedIcon from "@mui/icons-material/PersonOutlined"
import CalendarTodayOutlinedIcon from '@mui/icons-material/CalendarTodayOutlined';
import HelpOutlinedIcon from "@mui/icons-material/HelpOutlined"
import PieChartOutlineOutlinedIcon from "@mui/icons-material/PieChartOutlineOutlined"
import TimelineOutlinedIcon from "@mui/icons-material/TimelineOutlined"
import FolderSharedOutlinedIcon from '@mui/icons-material/FolderSharedOutlined';
import { Link as RouterLink } from 'react-router-dom'
import { useTheme } from '@mui/material'
import { ColorModeContext, tokens } from "./../theme"
import { useContext } from 'react';
import Logo from "./../assets/code2.jpg"

const SideBar = () => {
    const theme = useTheme();
    const colorMode = useContext(ColorModeContext);
    const colors = tokens(theme.palette.mode);
    const [selected, setSelected] = useState("Dashboard")

    const handleListItemClick = (text) => {
        setSelected(text)
    }

    const Item = ({ icon, text, to, selected }) => {
        console.log(selected === text);
        return (
            <ListItem key={text}
                selected={selected === text}
                disablePadding
                onClick={() => handleListItemClick(text)}
                sx={{
                    "&$selected": {
                        "& .MuiListItem.Mui-selected": {
                            backgroundColor: "blue",
                        }
                    },
                    "&$selected:hover": {
                        backgroundColor: "white",
                        '& .MuiListItem-root': {
                            color: "white"
                        }
                    }
                }}>
                <ListItemButton component={RouterLink} to={to}>
                    <ListItemIcon>
                        {icon}
                    </ListItemIcon>
                    <ListItemText selected={selected === text} primary={text}
                        sx={{
                            "&$selected": {
                                "& .MuiListItemText.Mui-selected": {
                                    color: "blue",
                                }
                            }}}                    />
                </ListItemButton>
            </ListItem>)
    }

    return (
        <Drawer sx={{
            width: 240,
            flexShrink: 0,
            '& .MuiDrawer-paper': {
                p: 2,
                width: 240,
                boxSizing: 'border-box',
                backgroundColor: `${colors.primary[500]}`,
            }
        }} variant="permanent" anchor="left">
            <Box textAlign="center" m="0 0 15px 0">
                <Typography variant="h3" color={colors.grey[100]} fontWeight="bold" sx={{ m: "10px 0 0 0" }}> ADMINIS</Typography>
            </Box>
            <Box mb="10px">
                <Box display="flex" justifyContent="center" alignItems="center">
                    <Avatar alt="logo" src={Logo} sx={{ width: 100, height: 100, cursor: "pointer"}} />
                </Box>
            </Box>
            <Box textAlign="center">
                <Typography variant="h2" color={colors.grey[100]} fontWeight="bold" sx={{ m: "10px 0 0 0" }}> Huvon Goodridge</Typography>
                <Typography variant="h5" color={colors.greenAccent[500]}>VP Fancy Admin</Typography>
            </Box>
            <List>
                <Item selected={selected} icon={<HomeOutlinedIcon />} text={"Dashboard"} to={'dashboard'} />
            </List>
            <Typography variant="h6" color={colors.grey[300]} sx={{ m: "15px 0px 0px 5px" }}>
                Data
            </Typography>
            <List>
                <Item selected={selected} icon={<PeopleOutlinedIcon />} text={"Team"} to={'team'} />
                <Item selected={selected} icon={<FolderSharedOutlinedIcon />} text={"Projects"} to={"projects"} />
            </List>
            <Typography variant="h6" color={colors.grey[300]} sx={{ m: "15px 0px 0px 5px" }}>
                Pages
            </Typography>
            <List>
                <Item selected={selected} icon={<PersonOutlinedIcon />} text={"Profile"} to={'profile'} />
                <Item selected={selected} icon={<CalendarTodayOutlinedIcon />} text={"Calendar"} to={'calendar'} />
                <Item selected={selected} icon={<HelpOutlinedIcon />} text={"FAQ"} to={'faq'} />
            </List>
            <Typography variant="h6" color={colors.grey[300]} sx={{ m: "15px 0px 0px 5px" }}>
                Charts
            </Typography>
            <List>
                <Item selected={selected} icon={<PieChartOutlineOutlinedIcon />} text={"Pie Chart"} to={'piechart'} />
                <Item selected={selected} icon={<TimelineOutlinedIcon />} text={"Timeline"} to={'timeline'} />
            </List>
        </Drawer>)
}

export default SideBar;

I've made numerous attempts to target the classes of the components I need to style, but none have been successful. I expected the changes in background color and text color when using the provided CSS properties, but unfortunately, it did not work as intended. Despite consulting the material UI website documentation, I was unable to find a solution to this issue.

Answer №1

When utilizing the sx prop to customize the selected component, consider incorporating styles into the &.Mui-selected and &.Mui-selected:hover property names.

For instance, you can refer to this simplified demonstration: stackblitz

<ListItemButton
  sx={{
    "&.Mui-selected": { backgroundColor: "hotpink", color: "#fff" },
    "&.Mui-selected:hover": {
      backgroundColor: "hotpink",
    },
  }}
></ListItemButton>

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

Steps to remove a package from the npm registry

Is it feasible to eliminate or erase a complete module from the npm registry? Please be aware that using npm -f unpublish does not permit the deletion of packages older than 24 hours. ...

Implement rotation in Three.js that mirrors the functionality of Blender

Is there a way to permanently change the default rotation of a mesh in three.js after it has been loaded? For example, if I load a mesh with a rotation of 0,0,0, can I then rotate it 90 degrees on the X axis and set this new rotation as 0,0,0? It's i ...

Utilizing the Sheet Elite API - Step-by-Step Guide for Sending Data to a Designated Sheet Through a POST Request

Recently, I've been working on a project that involves using the Sheet Best API to submit data directly to Google Sheets. However, I'm running into an issue where the data is only being sent to the first sheet out of three. Despite having all the ...

I wonder which Material Design repository is the source of this library

I am attempting to replicate the CSS style used in this particular Material Design-inspired web application: https://i.stack.imgur.com/utalx.png After exploring Materialize CSS and MUI, I have not been able to pinpoint the exact framework responsible for ...

The Google Map is unable to expand to fill the entire width of the column

I have exhausted all my efforts trying to troubleshoot this issue on my project's contact page. Currently, I have a layout with 3 rows containing columns within a Bootstrap 4 grid. The third row is supposed to display a Google Map within a column set ...

What is the correct location to define the "env" setting in the eslint.config.js file?

In 2022, ESLint rolled out a new configuration system called the "flat config" here. Check out the documentation for the new "flat config". | Old configuration system documentation here. The "flat config" documentation shows that the `eslint.config.js` ...

Clicking on the title link will open the content in an iframe, but the image

Having trouble with a previous post but I've created a codepen to illustrate the issue. Hoping someone can help me out! Check out the codepen here: "https://codepen.io/Lossmann/pen/GRrXyQY" ...

With NodeJs, Mongoose refrains from storing any data in the database

Recently, I encountered a puzzling issue with my code designed to store superhero names and powers in a database. Despite all the connections functioning correctly, I faced an unexpected challenge. When running mongod, I utilized the --dbpath C:/nodeproje ...

What is the process for applying a filter to a background image within the body of a webpage?

I'm attempting to apply a filter to the background image of the body element. Currently, I have implemented the following code: body { background: url("/img/congruent_pentagon.png"); color: white; font-family: "Raleway"; -webkit-filte ...

The inclusion of the <div> tag disrupts the functionality of the Material UI Grid

While attempting to enclose my element within a <div> that is nested inside the <Grid>, I realized that this was causing the <Grid> layout to break! Surprisingly, when I tried the same approach with Bootstrap grid system, this issue did n ...

Is it possible to show an image without altering the Box dimensions?

Hi there, I am currently working on designing a footer and I have encountered an issue. I want to add an image in a specific position, but when I do so, it affects the size of the box. I was wondering if there is a way to set the image as a background or b ...

Error: The connection to Node/Postgresql was refused at 127.0.0.1:5432. This occurred after connecting at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)

After running a Node server connecting to a Postgresql DB (via Knex) without issues, my laptop crashed. Upon restart, the DB connection stopped working, showing this error message: Error: connect ECONNREFUSED 127.0.0.1:5432 at TCPConnectWrap.afterConnect ...

Is it possible to incorporate Material-UI Lab into my project without having to install the Core components as well?

I'm hoping to incorporate the Slider component from Material UI into my React application. The Slider is one of the components housed in the 'Lab' package, which acts as an incubator for features that aren't quite ready for the core. n ...

Step-by-step guide on showcasing an image within the sidebar-wrapper CSS class

I am trying to include an image in the #sidebar-wrapper class using the code below: CSS: #sidebar-wrapper { background-image:url('/images/nav.jpg'); margin-left: -250px; left: 250px; width: 250px; position: fixed; height: 100%; ov ...

Adjust the text to fit neatly within a circular-shaped column container

I am currently working with Bootstrap 5 and I have a row with two columns positioned next to each other. My goal is to apply rounded borders to the left column while ensuring that the content remains within the div. Below is the code snippet: <div clas ...

Exploring the concept of 'JavaScript with Scope' within the MongoDB environment

Within the link provided at https://docs.mongodb.com/manual/reference/bson-types/, it discusses JavaScript with Scope as a potential data type found in documents. I have some inquiries: (1) Could you explain what exactly JavaScript with scope entails? ( ...

Encountering a problem while trying to start a create-react-app using npm

Currently delving into React and here's what I've accomplished so far: npm i -g create-react-app (completed successfully) create-react-app react-app (completed successfully) cd react-app npm start (encountered an error above) Here's the o ...

Persistent button positioned at the bottom of the page, remaining visible even when scrolling to the very end of the content

I am looking to add a floating button that remains in the same position relative to the content until the window is scrolled to a certain point, after which it sticks to the end of the content. In simple terms, I want the element to act as 'relative& ...

Retrieve information from Google Sheets to use in SVG map

While working on a local HTML page, I encountered an issue with my script. I am using the svgMap library to create a map of movies I have seen, pulling data from a Google Sheets document using the opensheet library. The JSON output looks like this: [{"Coun ...

Emphasize the most recent file during the document upload process and ensure the scroll bar moves accordingly to the document

I am currently working on a feature where the scroll bar should move to the newly uploaded document in a list of documents. When I upload a new document, I want the scroll bar to automatically move to that document. Currently, the highlighting changes to t ...