Is there a way to modify the styling for ListItemButton specifically when it is in a selected state?

My first experience with MUI involves trying to customize the styling of a button. After installing my project with default emotion as the styling engine, I attempted to override the existing styles using the css() method mentioned in the documentation: The css prop. However, it appears that the customization is not taking effect, even when testing on the provided example. I considered adding a custom CSS file to handle :select, but due to utilizing state in my component to toggle between selected and not selected states, this approach proved challenging.

import * as React from "react";
import Avatar from "@mui/material/Avatar";
import ListItemText from "@mui/material/ListItemText";
import ListItemButton from "@mui/material/ListItemButton";
import { useState } from "react";
import { css } from "@emotion/react";


const ProfileInfo = ({ userCredentials, userPicture }) => {
  const [selected, setSelected] = useState(false);

  return (
    <ListItemButton
      selected={selected}
      onClick={() => setSelected((prev) => !prev)}
      css={css`

        ::selection {
          color: #2e8b57;
        }
        :focus {
          color:#2e8b57;
        }
        :active {
          color:#2e8b57
        }
      `}
    >
      <Avatar
        alt={userCredentials}
        src={userPicture}
        sx={{ width: 24, height: 24 }}
      />
      <ListItemText primary={userCredentials} sx={{ marginLeft: 3 }} />
    </ListItemButton>
  );
};

export default ProfileInfo;

Answer №1

Check Out These Examples on Code Sandbox

I've created a similar example using Code Sandbox, which you can view at this link here. The demonstration showcases:

  • The css property
  • The sx property

Understanding the css Property

If you want to utilize Emotion's css prop in your code, there are a couple of steps to follow. First, include these lines at the beginning of the file where you're using the css prop:

  1. Add the following lines (also included in the example) at the top of your file to handle the css prop:
/* eslint-disable react/react-in-jsx-scope -- Unaware of jsxImportSource */
/** @jsxImportSource @emotion/react */
  1. Target the classes provided by Material UI for the List Item Button component. For example, if you want to style the List Item Button when it is selected, target the .Mui-selected class.

In this case, I assume you want to change the background color of the List Item Button instead of altering the text color. If you wish to modify the font color, simply replace 'background-color' with 'color'.

Putting it all together:

/* eslint-disable react/react-in-jsx-scope -- Unaware of jsxImportSource */
/** @jsxImportSource @emotion/react */
import * as React from "react";
import Avatar from "@mui/material/Avatar";
import ListItemText from "@mui/material/ListItemText";
import ListItemButton from "@mui/material/ListItemButton";
import { useState } from "react";
import { css } from "@emotion/react";

const ProfileInfo = ({ userCredentials, userPicture }) => {
  const [selected, setSelected] = useState(false);

  return (
    <ListItemButton
      selected={selected}
      onClick={() => setSelected((prev) => !prev)}
      css={css`
        &.Mui-selected {
          background-color: #2e8b57;
        }
        &.Mui-focusVisible {
          background-color: #2e8b57;
        }
        :hover {
          background-color: #2e8b57;
        }
      `}
    >
      <Avatar
        alt={userCredentials}
        src={userPicture}
        sx={{ width: 24, height: 24 }}
      />
      <ListItemText primary={userCredentials} sx={{ marginLeft: 3 }} />
    </ListItemButton>
  );
};

export default ProfileInfo;

Another Option: Utilizing the SX Property

The sx property can override styles for various Material UI components. You already apply this to the Avatar and ListItemText components in your example.

Here's how the equivalent code looks when using the sx property:

import * as React from "react";
import Avatar from "@mui/material/Avatar";
import ListItemText from "@mui/material/ListItemText";
import ListItemButton from "@mui/material/ListItemButton";
import { useState } from "react";

const ProfileInfo = ({ userCredentials, userPicture }) => {
  const [selected, setSelected] = useState(false);

  return (
    <ListItemButton
      selected={selected}
      onClick={() => setSelected((prev) => !prev)}
      sx={{
        "&.Mui-selected": {
          backgroundColor: "#2e8b57"
        },
        "&.Mui-focusVisible": {
          backgroundColor: "#2e8b57"
        },
        ":hover": {
          backgroundColor: "#2e8b57"
        }
      }}
    >
      <Avatar
        alt={userCredentials}
        src={userPicture}
        sx={{ width: 24, height: 24 }}
      />
      <ListItemText primary={userCredentials} sx={{ marginLeft: 3 }} />
    </ListItemButton>
  );
};

export default ProfileInfo;

Answer №2

Upon investigation, it appears that MUI components do not adhere to traditional CSS rules. Instead, they have a predetermined set of CSS rules that are customizable. For more information, you can refer to https://mui.com/material-ui/api/list-item/#props.

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

Exporting two functions in JavaScript

Currently utilizing React, Redux, and experimenting with Material-UI integration. The example codes provided by Redux and Material-UI libraries include an 'export' statement at the end. Redux: export default connect(mapStateToProps, actions)(my ...

Encountering: Server Failure TypeError: Unable to access attributes of an undefined element (accessing 'length') within NextJS

Why is the component rendering correctly but the browser console is throwing an error? How can I resolve this issue? in firebase.js import * as firebase from "firebase/app"; const firebaseConfig = { apiKey: "my api code", authDomain: "mywebs ...

What types of modifications do ViewChildren and ContentChildren QueryLists keep an eye out for?

Imagine you come across the following lines of code: https://i.stack.imgur.com/7IFx1.png And then, in a different section, you stumble upon this code block: https://i.stack.imgur.com/qac0F.png Under what circumstances would () => {} be executed? Wha ...

Tips for passing specific properties to the Next.js error page when it cannot be found

When working with Nextjs, you can handle 404 errors by using the following code: return {notFound: true}; However, if you want to send additional data to your custom 404 page in order to display a customized error message to users, you can do so like this ...

What are some creative ways to animate a highlight effect on a CSS

I'm struggling to implement a sliding underline effect for my top navigation bar on hover. I've tried using transitions and keyframes, but so far it's not working as expected. My current attempt only triggers the effect on the parent elemen ...

TS7053: The element is implicitly assigned an 'any' type as the expression of type 'string' cannot be used to index the type '{ username: string; email: string; '

Having trouble incorporating TypeScript into a custom React Form Component, and I keep encountering an error that I can't seem to resolve. Error message TS7053: Element implicitly has an 'any' type because expression of type 'string&apo ...

Styled-Component: Incorporating Variables into Styled-Component is my goal

Currently, I am working on an app and have created a separate file for styling. I decided to use style-components for custom CSS, but faced an issue where I couldn't access variables instead of HEX values. Even after storing color values in a variable ...

Creating a unique look for unordered list items in a dropdown navigation

I'm currently working on creating a drop-down menu using nested unordered lists. The functionality of the menu is all set, but I'm running into some styling issues. The main link that triggers the drop-down should have a blue background with whit ...

How can the dot badge in Material-UI be enlarged?

I'm in need of a badge component that serves as an indicator without displaying any values. I opted for the dot variant, but it's too small for my liking. I tried modifying it with CSS, but it doesn't seem to be working as expected. Any sugg ...

Why is my CSS and Bootstrap full-page image not displaying properly?

I've been struggling to get a full-page image to display on my website and resize responsively across different screens. I've searched through w3schools and Stack Overflow for solutions, but no matter what I try, it just doesn't seem to work ...

Develop an XML document that includes CSS and DTD seamlessly incorporated

Could someone please provide me with a short code example of an XML file that includes both a DTD and CSS styles all in one file? Just need one element as an example. I'm new to XML and can't seem to find any examples with both XML and CSS comb ...

An issue occurred while attempting to execute the npm start command

While attempting to create a React project, I used npx create-react-app hello-react --use-npm and then navigated to the hello-react directory using cd hello-react. However, when I tried to run npm start, I encountered the following error: npm ERR! code ENO ...

What is the best way to integrate Tawk.to into a React application while using typescript?

Having some issues integrating tawk.to into my website built with React and TypeScript. I have installed their official npm package, but encountered an error message: import TawkMessengerReact from '@tawk.to/tawk-messenger-react'; Could not fin ...

Using React JS and Material UI to showcase N elements within a dynamically sized container

The task I am attempting should be straightforward, but I am struggling with implementing it correctly using Material UI in ReactJS: I have a Card component that includes an image, title, description, and buttons. This Card element has a set width and hei ...

The Zustand store does not reflect changes when the URL is updated

I have a Zustand store connected to the URL. See the code snippet provided below. import { create } from "zustand"; import { persist, StateStorage, createJSONStorage } from "zustand/middleware"; const pathStorage: StateStorage = { ge ...

Stop all animations in JS and CSS

Looking for a way to halt all CSS and JavaScript animations, including canvas and webGL effects, on a specific webpage. Some animations can cause slow performance on certain browsers like Opera and Firefox, so I'm seeking a code snippet or guidance o ...

I am having difficulty organizing my text into two grid columns and aligning it in the center

.hero { display: grid; grid-template-columns: repeat(2, 33.45rem); grid-template-rows: 12.5rem; border-bottom: .05em solid #05d31f; width: 69.8rem; height: 16.5rem; } .hero-title { grid-row-start: 1; grid-column-start: 1; } .hero-title h ...

What steps can be taken to eliminate a npm install error?

I have been attempting to execute the following project: https://github.com/kentcdodds/react-in-angular This repository serves as an illustration of incorporating React into AngularJS. It consists of three tags that demonstrate the process of transitio ...

Utilizing Conditional CSS Classes in React Material-UI (MUI) 5

I am in the process of migrating from React material-ui 4 to MUI 5. How can I implement this particular design pattern using the new styled API (or any other suitable method)? My project is written in Typescript. const useStyles = makeStyles(theme => ...

- Bullet point: Table heading alignment variation

When it comes to centering a <th> element inside an <li>, different browsers have different approaches. In Internet Explorer, Edge, and Safari, the <th> is center-justified. However, in Chrome, Firefox, and Opera, it's left-justifie ...