Changing the color of MUI Typography when selected

Struggling to modify the styling of the Typography component nested inside a MenuItem. Unable to apply styles to ListItem as intended

Check out my code here: https://codesandbox.io/s/dztbc?file=/demo.tsx:1481-1804

Desired behavior: Change styling on selection. Access text should turn green and have bolder font-weight when selected

Current behavior: Styling only works for 'light mail' when selected. How can I fix this?

Answer №1

MenuItem allows for a style rule to be applied to the selected item using the classes prop with the key name selected. In order for this functionality to work, the item must also have a boolean prop called select, indicating whether the item is selected or not.

const StyledMenuItem = withStyles((theme) => ({
  root: {
    "&:focus": {
      backgroundColor: theme.palette.primary.main,
    },
  },
  selected: {
    color: "red",
  }
}))(MenuItem);
export default function CustomizedMenus() {
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const [selected, setSelected] = React.useState(null);

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleMenuItemClick = (e, index) => {
    setSelected(index);
  };
  const menuArr = [
    {
      Icon: SendIcon,
      text: "Sent mail"
    },
    {
      Icon: DraftsIcon,
      text: "Sent mail"
    },
    {
      Icon: InboxIcon,
      text: "Inbox"
    }
  ];

  return (
    <div>
      <Button
        aria-controls="customized-menu"
        aria-haspopup="true"
        variant="contained"
        color="primary"
        onClick={handleClick}
      >
        Open Menu
      </Button>
      <StyledMenu
        id="customized-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleClose}
      >
        {menuArr.map((item, index) => (
          <StyledMenuItem
            selected={index === selected}
            onClick={(event) => handleMenuItemClick(event, index)}
          >
            <ListItemIcon>
              <item.Icon fontSize="small" />
            </ListItemIcon>
            <ListItemText primary={item.text} />
          </StyledMenuItem>
        ))}
      </StyledMenu>
    </div>
  );
}

For a live demo, click here:
https://codesandbox.io/s/material-demo-forked-wtsrj?fontsize=14&hidenavigation=1&theme=dark

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

The React Typescript error message: "Type '' is not compatible with type 'null'"

I have started working on a simple todo app using React and TypeScript. As I am creating a context, I encountered an error regarding the value of the content provider. <TodoContext.Provider value={contextValue}>{children}</TodoContext.Provider> ...

CarouFredSel Transition Troubles

I am currently using CarouFredSel to create an image carousel, but I am encountering some issues with the transitions between items. My goal is to incorporate simple HTML elements into the carousel instead of just plain images. However, when I attempt to ...

Want to put Jest and Enzyme to the test?

Is there a way to effectively test this function using Jest and Enzyme? addProducts = id => { toast.success("Product added", { position: toast.POSITION.TOP_RIGHT }); history.push(`/product/${id}`); }; I attempted to use this code s ...

Create an eye-catching hexagon shape in CSS/SCSS with rounded corners, a transparent backdrop, and a

I've been working on recreating a design using HTML, CSS/SCSS in Angular. The design can be viewed here: NFT Landing Page Design Here is a snippet of the code I have implemented so far (Typescript, SCSS, HTML): [Code here] [CSS styles here] [H ...

Creating a specific order for Arabic strings in HTML is simple and can be done by utilizing

I need to adjust the ordering of a datetime written in Arabic numbers. I must use an Arabic string and currently have the following C# code written in Arabic: std.InnerText = "17-02-2016"; The current output is in Arabic numerals, displayed as ٢٠١٦- ...

React Native: Picker value remains static

I'm encountering an issue where the value of the picker does not change when I select a new value from it. This problem started occurring after I added the onValueChange function. If anyone has any insights or suggestions on how to resolve this, I wou ...

Tips for creating a script that compiles all SCSS files into CSS within a Vue 3 project

Within my project, there exists a file named index.scss located in the src/assets/styles directory. Adjacent to this file are multiple folders housing SCSS files that are ultimately imported into index.scss. My objective is to devise a script within the pa ...

Change the filter items operator to "OR" from "AND"

Currently tackling the XGrid project, I'm faced with the task of filtering rows based on checkboxes selected on my page. I've been attempting to pass items into the filterItems prop to create multiple filters, but I'm struggling to figure ou ...

Is it possible to show one element while hiding others upon clicking using JavaScript?

Concept My idea is to create a website with a navigation menu where only one section is visible at a time. Each section would become visible upon clicking a specific button in the navigation bar. Challenge I attempted to achieve this using the following ...

Div with wide width and captivating perspective

Recently, I've been experimenting with perspective and 3D transformations, and I've realized why my div isn't displaying at full width despite setting it in the CSS. However, I'm interested in creating a responsive layout where the div ...

Tips for maintaining state URL persistence after a page refresh in Next.js 13 when utilizing next-usequerystate

Currently, I am using the next-usequerystate library with Next Js 13. However, I have encountered an issue where the state on the URL is lost when I refresh the page. The initial URL looks like this: localhost:3000/?page=1&genres=tree But upon refres ...

Tips for positioning the popup ul in relation to its parent li

How can the pop-up ul be positioned in the center of the parent li using CSS? * { margin: 0; padding: 0; } #track-nav { margin-left: 50px; margin-top: 50px; float: left; width: 100%; list-style: none; font-weight: bold; margin-bottom: ...

Resolving Overflow Issue with Images in Grid Item using React and Material UI

My image is overflowing past the grid boundary, and I suspect it may be due to sizing issues as I have specified that the image cannot exceed sm={6}, which it does not adhere to. The code snippet containing the image is provided below. class Intro extends ...

Implementing a button row and content alignment next to an image using Bootstrap or CSS

Ensure that the product detail page features a row with labels and buttons, positioned to the right of the image within Bootstrap columns. I have utilized Bootstrap 3 for this page layout. However, upon implementation, I encountered an issue whereby the b ...

The Safari browser is plagued by a flickering issue with CSS perspective flip animations, even when using the back

I'm facing an issue with Safari (both desktop and iOS) related to a simple CSS flip animation. Despite searching through similar posts and answers, I haven't found a solution yet and am in need of a fresh perspective. Essentially, I am creating ...

What is the syntax for declaring a variable in JSX?

I'm working with code that retrieves data from an Apollo Server backend in the format shown below: { name: 'geodude', url: 'https://pokeapi.co/api/v2/pokemon/74/' }, { name: 'graveler', url: 'https://pokeapi.co/api/v ...

A guide on toggling the password input type between text and hidden in a React application

I am facing an issue with toggling the input type between password and text to display the password in a login form. The expected functionality is that clicking on the eye icon next to the password input should reveal the password in plain text, but this i ...

In Stripe.js, the background color and height of the credit card input cannot be customized

I'm struggling with customizing the appearance of a Stripe credit card input within my Vue.js application. I want to adjust the background color to #f1f1f1 and set the height to 60px, but despite trying both base styles and css, I can't seem to g ...

Pagination CSS may fail to function properly in Chrome after an AJAX call is returned

Having an issue with CSS not getting applied correctly after making an AJAX call with pagination. The problem seems to be specific to Chrome, as it works fine in Firefox. When inspecting the element, the CSS is present but not being applied properly until ...

Issue with state not reflecting changes from document snapshots

I am facing a challenge with assigning data to useState by fetching data using reference type value from firebase. const [preOil, setPreOil] = useState([]); const [oilChange, setOilChange] = useState([]); useEffect(() => { getDocs(query(collection(db, ...