Is it possible to modify the font color of a specific MenuItem in material-ui?

I've scoured every corner of the internet, but I'm still stumped by this question: How can I tweak the text color (not the background) for a selected or hovered MenuItem? I know the solution lies within useStyles, but my attempts thus far have been fruitless. I've experimented with various CSS approaches, but material-ui seems to have its own unique naming conventions.

const StyledMenuItem = withStyles(theme => ({
    root: {
        "&:focus": {
            backgroundColor: theme.palette.primary.main,
            "& .MuiListItemIcon-root, & .MuiListItemText-primary": {
                color: theme.palette.common.white
            }
        },
        paddingTop: "4px",
        paddingBottom: "4px",
        paddingRight: "4px",
        paddingLeft: "4px",
        margin: "4px",
        fontSize: "0.8rem",
        lineHeight: "1",
    },
    searchMenuItem: {
        paddingTop: "2px",
        paddingBottom: "2px",
        selectedTextColor: "#ffffff",
  }
}))(MenuItem);

Could someone please guide me on what needs to be added to useStyles in order to change the selected text of a menuitem to white?

I've attempted adding things like

&.selected: {
  color: "#ffffff",
}

to the menuitem classes without success. Any assistance would be greatly appreciated!

Answer №1

To pinpoint the specific class used on selected elements, utilize a CSS selector and observe the console output. Based on my interpretation of the documentation, this snippet should cater to your needs:

&.Mui-selected: { color: "#ffffff", }

Answer №2

Essentially, I experimented with the documentation to override the CSS styles but encountered issues that prevented it from working as expected. Although there is a comprehensive solution available, I found it cumbersome to navigate through and preferred using CSS for its simplicity.

Instead, I opted for a different tactic by leveraging the specificity of CSS, which ultimately led to success.

For demonstration purposes, here's a jsfiddle implemented in a react environment (though the language used is not critical – focus on the CSS).

The strategy involved inspecting the menu elements in the developer tools to identify their classes and customizing them effectively using CSS rules.

Here's an excerpt of the CSS code:

.horiz-menu div:hover { /* Enhancing specificity */
   color: red;
}

And here's a snippet of the accompanying JS code:

const { Menu, MenuItem, MuiThemeProvider, getMuiTheme } = MaterialUI;

class Example extends React.Component {
  render() {
    return (
     <Menu className="horiz-menu">
       <MenuItem primaryText="Home" />
       <MenuItem primaryText="Test Menu 1" />
       <MenuItem primaryText="Test Menu 2" />
       <MenuItem primaryText="About" />
     </Menu>
    );
  }
}

const App = () => (
   <MuiThemeProvider muiTheme={getMuiTheme()}>
   <Example />
   </MuiThemeProvider>
);

ReactDOM.render(
  <App />,
    document.getElementById('container')
);

Answer №3

If you're struggling with changing the text color of a selected menu item, remember to utilize the &hover command from material-ui.

For example, if you want white text on a dark background for a selected menu item (assuming your primary theme has a dark background color for selected items), follow these steps:

const StyledMenuItem = withStyles(theme => ({
    root: {
        "&:focus": {
            backgroundColor: theme.palette.primary.main,
            color: theme.palette.common.white, <===ADD THIS LINE
            "& .MuiListItemIcon-root, & .MuiListItemText-primary": {
                color: theme.palette.common.white
            }
        },
    }
}))(MenuItem);

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

Create a border around the text using a strokeoutline

I'm attempting to apply an outline to text using CSS. The issue I'm facing is that the shadow doesn't work well for perfectly stroked text. Is there a way to achieve this with just CSS? Below is the code snippet I am currently using: . ...

The failure of the Selenium script can be attributed to the presence of the AJAX

Struggling to automate an application with an AJAX loader causing issues? Getting the dreaded error message about element not being clickable when the loader is active? Frustrating, right? But fear not! I have devised a clever solution in the form of a wr ...

Accessing a local JSON file in a ReactJS application without the need for a local server installation

I am encountering an issue with the file structure of src/resource/file.json.https://i.sstatic.net/qjITH.jpg 1. Utilizing load-json and require to handle the file: class App extends Component{ constructor(props) { super(props); ...

A little brain teaser for you: Why is this not functioning properly on Google Chrome?

Have you noticed that the code below works perfectly in Firefox, but fails in Chrome when trying to 'post' data? $("a").click(function() { $.post("ajax/update_count.php", {site: 'http://mysite.com'}); }); Hint: Make sure you are us ...

Issue with Material UI Menu not obtaining the accurate ID

My table requires an action menu button, but when it renders, it copies the last ID of the array instead. I'm struggling to identify the root cause of this issue despite trying multiple solutions that didn't address the problem. Below is the cod ...

Variety of HTML tags yet identical ID

Is it possible to have two elements with different types – such as a div and an ul with the same id in HTML? Here is an example of HTML code: <div id="articleOptions"> <ul id="articleOptions"> <li>Share</li> ...

Tips for inserting the <style> element within a Vue.js component

Currently working with Vue.js v2, I am facing an issue where I have a CSS stylesheet stored as a string in a variable. import sitePackCss from '!!raw-loader!sass-loader!../../app/javascript/styles/site.sass'; I am trying to generate a <style& ...

Fetching data dynamically using ajax as you scroll

Currently, I am using the jQuery Tools Plugin to create an image slider. However, I am facing a challenge with loading a large number of images all at once. Since the slider is coded in JavaScript, I am not sure how to control the scroll position. I would ...

Why isn't my state being updated properly with React's useEffect, useState, setInterval, and setTimeout functions?

const handleClick = () => { if (!activated) { if (inputValue == '') { return } if (!isNodeInGraph(graph, inputValue)) { return } } setActiv ...

The default setting for the calendar picker indicator should be enabled

Whenever I hover my mouse over it, an indicator pops up, but I want to make it the default <input type="date" class="form-control" name="Date" [(ngModel)]="opening_date" (ngModelChange)="Operating()" style="width:550px" required> inp ...

"Exciting features of NextJS 13 include the utilization of client component callback functions

Let's say I need to develop a custom Table React component with server-side pagination and sorting features, which can be reused in different parts of the application to display various types of data. In my create-react-app project, I would create a ...

Automatically deliver a message regularly at set intervals on Discord across all groups and guilds

Currently, I am developing an event-bot to use in multiple Discord groups. Here is the code snippet I have been working on: if (command === "init") { message.channel.send("BunnBot starting..."); var interval = setInterval (function () { me ...

Displaying the action.type in Components with React and Redux: A comprehensive guide

I am looking for a way to display the status of the action.type in my component when it is triggered. This will help me show whether an action has been successfully passed or not (when catch is triggered). Do you have any suggestions on how I can achieve ...

The MUI next Tooltip fails to display upon hovering

While using Material-UIv1.0.0-beta.34 Tooltip with Checkbox and FormControlLabel, I noticed that the tooltip works as expected when hovering over the label in one case. However, when I tried creating a new component(custom) with FormControlLabel and Checkb ...

The module specifier "logrocket" could not be resolved, make sure to use either npm or

I'm currently having an issue with initializing LogRocket. I followed the steps from the official documentation: I successfully installed it using node: npm i --save logrocket However, when trying to initialize it on my page earlier with: < ...

Activate onbeforeunload when the form is not submitted

Currently, I have a form that is submitted using PHP with three different submit actions: Save and Continue Save and Exit Exit without Saving The goal is to trigger an "OnBeforeUnload" alert if the user does not click on any of the form actions. This al ...

Dealing with CORS, IIS7, and PHP - Overcoming the Access-Control-Allow-Origin obstacle

I am attempting to enable another local host (such as javascript.dev) to make a xhr request to this particular host, which operates on an IIS7 server. When I perform a curl -I command, the headers I receive are as follows: HTTP/1.1 200 OK Content-Length: ...

Pinia alert: The function "getActivePinia()" was invoked without an active Pinia instance. Could it be possible that you overlooked installing Pinia?

Despite having an action that dynamically updates the 'pending' state based on whether the data has been fetched, reactivity seems to be non-functional when used inside the component. This issue is referenced in the official Pinia documentation: ...

Intellisense in VS Code is not functioning properly for vitest matchers

After transitioning my codebase from cra to vite and integrating vitest, everything seems to be running smoothly. However, I am encountering an issue with suggestion prompts in VS Code while performing assertions such as expect(getByText(text)).toBeInTheDo ...

A single pixel border surrounding an odd number of divs

I've been struggling with a persistent issue and I'm determined to find a solution. My goal is to achieve the following design using css: https://gyazo.com/c8ae39ebc4795027ba7c1067a08d3420 Currently, I have an uneven number of divs styled as fo ...