Home > Enterprise >  Issue trying to override mui theme in Reactjs
Issue trying to override mui theme in Reactjs

Time:12-13

I have a navbar with some list items and I want to override the style of MuiListItemText when MuiListItemButton is selected. I can override the hightlight but can't do it with the text or the icon. I can override the ListItemText but all of them, I just want to override if 'selected' (Mui-selected). I'm using Mui 5.2.0. This is my approach.

const Theme = createTheme({
    components: {        
         MuiListItemButton: {
            styleOverrides: {
              root: {
                borderRadius: '4px',
                padding: '12px',
                '&.Mui-selected': {
                  backgroundColor: '#F2F2EA',

                  MuiListItemText: {
                    styleOverrides: {
                      secondary: {
                        color: 'red',
                             ...

CodePudding user response:

You should define the overriding theme structure in the same depth.

const Theme = createTheme({
    components: {        
         MuiListItemButton: {
            styleOverrides: {
              root: {...}
            }
         },
         // it should be another component, not a nested structure
         MuiListItemText: {
            styleOverrides: {
              secondary: {
                ...

And you can customize an individual component by using sx prop, styled-components, or makeStyles API.

https://mui.com/customization/how-to-customize/

Here's an example using styled-components.

const CustomListItemButton = styled(ListItemButton)(() => ({
  borderRadius: '4px',
  padding: '12px',
  '&.Mui-selected': {
    backgroundColor: '#F2F2EA',
    ...
}));

CodePudding user response:

Try this:

import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles';

CodePudding user response:

I don't think it's the best approach but I was able to do it with something like this:

<ListItemText
  secondary={
    <Typography
      variant="body2"
      style={selected === '/' ? { color: 'red' } : { color 'green' }>
        Item Text</Typography> } />
  • Related