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

Exploring Middleware with React Hooks

As I navigate through my react-native app, I find myself utilizing redux for state management. The concept of hooks has caught my attention lately and I am eager to incorporate them into the application. One challenge I face is managing multiple instances ...

The reasons why your React app may be malfunctioning on Internet Explorer browser

Having trouble getting my React App to work in Internet Explorer. I've tried various solutions but none seem to be working. npm i react-app-polyfill --save To address the issue, add the following files to index.js: import 'react-app-polyfill/i ...

Ways to retrieve the content from a textfield

Is there a way to retrieve text from a textfield in material UI without using the onChange method? It just seems odd that I would need to constantly track the value with onChange in order to use it for any other purpose. I decided to search for solutions ...

React is throwing a parsing error due to the incorrect use of braces. Remember, JSX elements must be wrapped in an enclosing tag. If you were trying to include multiple elements without a parent tag, you can use a JSX fragment

Having recently started working with React, I came across this code snippet return ( <div> dropdown ? (<li className='goal-list-item' onClick={() => setDropdown(!dropdown)}>{goal.name}</li>) : ...

Utilizing React hooks to dynamically toggle a class within a component

While similar questions have been raised previously, none seem to address my specific issue. Most references involve class components that do not align exactly with what I am attempting to achieve. My goal is to toggle two components on and off with a simp ...

What causes the Ref object to prompt a rerender in this code?

Check out the amazing react-native animation demo on https://reactnative.dev/docs/animated const fadeInOut = useRef(new Animated.Value(0)).current // Initial opacity value: 0 React.useEffect(() => { Animated.timing( fadeInOut, { ...

Attempting to Send an Ajax Request and Utilize the Result within a React Component

I am having issues with my tweet box component. I have a submit function that triggers the getAllTweets function when called. The problem is that I am unable to capture the value of the field and pass it on to the getAllTweets function in order to create ...

Sending a GraphQL variable to the Material UI component

Currently, I am working with React Typescript and incorporating an Autocomplete Material UI component into my project. The main goal is to populate query suggestions within the Autocomplete component. The graphql queries are structured like this: Query D ...

Having trouble getting custom select to work with CSS in Firefox?

I want to customize the button (down arrow) located in the right corner of the select box. The HTML code is as follows: <div class="buscaSelect"> <select name="oper"> <option value="value1">Value 1</option> < ...

Utilizing the fetch API in React with hooks

I'm looking to create a basic Fetch request (or axios request) and then display the results in a list. Currently, I'm utilizing useState and useEffect, although I believe there's an error in my implementation. function App() { const [to ...

Show the React component once the typewriter effect animation is complete

Hello there, I am looking to showcase my social links once the Typewriter effect finishes typing out a sentence in TypeScript. As someone new to React, I'm not quite sure how to make it happen though. Take a look at the code snippet below: ` import ...

Strange behavior of dropdown submenu

I've encountered an issue where my child's ul li elements are not behaving as expected, despite following advice from other sources. After days of debugging with no success, I am unable to pinpoint the problem. The image showcases the issue perfe ...

React Semantic UI - adjusting spacing on mobile screens with marginRight

I have implemented a web app using React Semantic UI and the Heroku React create app buildpack. However, I am facing an issue where there is always a margin on the right side of the fluid container. I checked Chrome's inspector but could not locate t ...

The width of the Div element is not following the specified dimensions, and it also has an unspecified margin

Check out my code snippet at: http://jsfiddle.net/8z4aw/ I'm trying to create a table-like layout using div elements, but for some reason the browser is not respecting the specified widths and seems to be adding an unwanted right margin. Where is thi ...

Encountering a 500 internal server error after deploying due to utilizing getServerSideProps in Next.js

When trying to redeploy my website on Vercel, I added getServerSideProps to my index.js file. However, I encountered an error that I am not familiar with. The program works perfectly on localhost. This is the getServerSideProps code that I added: export a ...

Different ways to showcase multiple columns in a bootstrap dropdown

In my React JS application, I successfully implemented a bootstrap dropdown control (located below Tag) that meets my needs. However, I am now seeking guidance on how to display multiple columns in the dropdown menu. Specifically, I would like to show bo ...

One of the paragraphs refuses to align with the others by floating left

Greetings everyone! This is my first time posting here, although I have been a regular visitor looking for answers on this site. Hopefully, someone can assist me with my current issue. Let me explain my problem: I've been attempting to align all the ...

How can I create a static navigation bar and sidebar using Bootstrap 4?

Currently, I am utilizing HTML, Javascript, Bootstrap, and CSS to develop a fixed navbar and sidebar for our system. My objective is to ensure that the navbar and sidebar remain fixed even when users scroll down the page, while also maintaining responsiven ...

Utilizing CSS3 transformation perspective on a div element when the window has finished loading

Greetings everyone. I've been experimenting with CSS3 perspective, and I'm encountering an issue where it only shows up while the window is loading. Here's a fiddle ._red{ background-color:#f00; display:block; width:100px; ...

In this tutorial, we will explore the process of creating a dynamic page using Catch-all Segments in

Creating dynamic URLs such as: /gallery/ /gallery/a /gallery/b /gallery/c To achieve this, I implemented the following code in a file named: pages/gallery/[slug].js const Gallery = ({ CurrentPage }) => { return ( <> <h3 ...