Tips on customizing the selected icon color in Material-UI's BottomNavigationAction styling

I'm facing an issue with Material-UI styled components and could use some assistance. My goal is to create a BottomNavigation bar in React using Material-UI v5 where the selected option's icon displays in red (#f00) while the unselected icons show in green (#00f). I've been attempting to achieve this by utilizing the styled function to customize a themed component for BottomNavigationAction, as outlined in the documentation: styled(). However, I'm encountering a problem – the selected button's icon isn't reflecting the correct color and instead continues to display the default color. I'm unsure if I'm misusing the styled function or overlooking something obvious. Any guidance would be greatly appreciated!

PS: I apologize for not being able to directly post the image due to insufficient reputation

The BottomNavigation setup is as follows:

const BottomNav = () => {
        return(
            <BottomNavigation
                showLabels
                value={value}
                onChange={(event, newValue) => {setValue(newValue)}}
            >                
                <TabBarButton 
                    id='Home' 
                    label='Home' 
                    icon= {home_icon? <AiFillHome size = "30" /> : <AiOutlineHome size='30'/> } 
                    onClick={
                        (value)=>{
                            iconHandler(value.currentTarget.id)
                        }
                    }
                />

                <TabBarButton
                    id='Documentos' 
                    label='Documentos' 
                    icon= {documentos_icon? <RiEditBoxFill size='30'/> : <RiEditBoxLine size='30'/>} 
                    onClick={
                        (value) =>
                            iconHandler(value.currentTarget.id)
                        }
                    }
                />
            </BottomNavigation>
        );
    }

Initially, I attempted defining the TabBarButton component like this:

import {BottomNavigation, BottomNavigationAction} from "@mui/material";
import { styled} from '@mui/system';

// Styled BottomNavigationAction
const TabBarButton = styled(BottomNavigationAction)({
    root: {
        color: '#f00',
    },
    
    selected: {
        color: '#0f0',
    }
});

However, the rule names root and selected did not produce the desired results, applying the default colors instead - you can view the outcome here

Subsequently, I adjusted them to apply to the Global Class instead following the BottomNavigationAction CSS:

// Styled BottomNavigationAction
const TabBarButton = styled(BottomNavigationAction)({
    color: '#0f0',
    '.Mui-selected':{
        color: '#f00',
    }
});

This modification worked for the unselected icons and labels as displayed here. But the selected icon 'Home' still retains the default colors. In an attempt to resolve this, I experimented with a variation of the solution provided in this post Bottom Navigation Material UI Override

// Styled BottomNavigationAction
const TabBarButton = styled(BottomNavigationAction)({
    color: '#0f0',
    '.Mui-selected, svg':{
        color: '#f00',
    }
});

However, this adjustment affects both icons resulting in the outcome shown here

Answer №1

It is important for the TabBarButton component to include the '&.Mui-selected' selector in order for the styles to be applied correctly. Without it, using just '.Mui-selected' will only affect nested elements:

I have tested this example on: stackblitz

// Styling for BottomNavigationAction
const TabBarButton = styled(BottomNavigationAction)({
  color: 'royalblue',
  '&.Mui-selected': {
    color: 'crimson',
  },
});

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

Loading screen while all files and audio are being loaded

My JavaScript code is responsible for displaying and playing audio on my website. Unfortunately, the load time of the page is quite slow. To address this issue, I decided to follow a tutorial on installing a preloader, which can be found at . Although I ...

React Star Rating Component: Issue with Image Display

To all who contributed their time and effort in responding to my previous question, I offer my sincerest apologies. Initially, I had assumed that assistance wouldn't be forthcoming, so I started working on the issue myself. As a result, I have made si ...

Tips on personalizing MUI X Data Grid Toolbar to exclusively display icons

`function EnhancedToolbar() { return ( <GridToolbarContainer> <GridToolbarIcon icon={<FilterListIcon />} /> <GridToolbarIcon icon={<ViewColumnIcon />} /> <GridToolbarIcon icon={<SettingsEthernetIc ...

What is the best method to eliminate whitespace in mobile view when utilizing the <Image /> tag in Next.js?

I am currently developing a website using Next.js. I have used the <Image /> tag to display images on the site. On mobile view, I noticed some white space around the image components, while on desktop everything looks fine. Upon checking the network ...

What is the best way to efficiently handle onChange events for multiple input checkboxes in Reactjs?

When I attempt to assign an onChange event listener to a group of checkboxes, clicking on one checkbox results in all checkboxes being clicked and the conditional inline styles that I defined are applied to all of them. Here is the JSX code snippet: class ...

Incorporate an Array of Objects into the UseState hook with an initial value

I have encountered an issue with the following error message: "Error: Objects are not valid as a React child (found: object with keys {fzfvhv76576, user }). If you meant to render a collection of children, use an array instead." I have been attem ...

Tips for selecting React component props based on a specific condition

Here is a React component that I have: <SweetAlert show={this.props.message} success title={this.props.message} onConfirm={this.props.handleCloseAlert}> </SweetAlert> Upon using this component, I receive the following alert ...

What is the best way to change the color of the Button?

In the documentation, it mentions that the color property accepts enums of "default", "inherit", "primary", "secondary". I am looking to use a different color other than "primary" and "secondary". One way to achieve this is by leveraging the "Overriding wi ...

Having difficulty troubleshooting the /app router application on version 13.4.x

Having trouble debugging a server-side process in my Next.js app that uses the /app router. To reproduce the issue, simply create a new Next.js app with npx create-next-app and select the app router option. I've attempted to attach a debugger to the ...

Different ways to modify the CSS file of the bx-slider plugin for multiple sliders within a single webpage

Currently in the process of building a website using bx slider. I am looking to incorporate three sliders onto a single page for sliding HTML content. Initially, I added a bx slider to the page and customized it using CSS. I made modifications within jqu ...

The Mui Switch track color fails to change when checked

I'm looking to customize the colors of the track for both checked and unchecked states. Currently, the track color is working for the unchecked state but defaults for the checked state: Checked State: https://i.stack.imgur.com/eGV4a.png Unchecked S ...

Determine how the scale of a transform changes over time by calculating the function of elapsed time [ transform: scale(x, y

I am currently working on a container that can be expanded and collapsed simply by clicking on a chevron icon. The functionality to collapse or expand the container resides within a function called transformAnimation. This function code closely resembles t ...

NX monorepo: project utilizes the source files of the library rather than using the files from the distribution folder

Here is the issue I'm facing: I am using NX for a monorepo. Within this setup, there is an application built in AngularJS (using webpack) which utilizes a library that generates web components (built with React). import { test } from "@lib/someli ...

What is the best way to change an array element into a string in TypeScript?

Within my Angular 2 component, I am utilizing an array named fieldlist which is populated by data retrieved from an http.get request. The array is declared as follows: fieldlist: string[] = []; I populate this array by iterating through the JSON response ...

Error: Unable to use the property 'basename' in the destructured object from 'React2.useContext(...)' because it is null

After a long break from working with React-Router, I'm diving back in with v6 for the first time. The tech stack of my application includes: Vite React Material-UI My troubleshooting steps so far have included: Searching online resources Revisiting ...

RStudio Connect now automatically inserts CSS code into cells when updating

My current project involves creating an app for holiday requests. The main page of the app is displayed like this: At the bottom right corner, you'll notice a column labeled "Accepted?" which displays either "OK" or "DENIED" in different colors. When ...

Can a component be updated immediately after shouldComponentUpdate, but before the subsequent component's shouldComponentUpdate is triggered?

I am currently enjoying using React, but I have encountered a challenge with a crucial part of my application. Whenever an item is mounted or updates are flushed to the DOM, I need to perform specific checks on the final HTML before proceeding further (su ...

Upon the initial data retrieval, everything seems to be working fine. However, when the user transitions to chatting with another user, the state value does not reset and instead shows a combination

Exploring the world of react.js and node.js, I am currently working on developing a chatting application with the integration of socket.io. The issue I'm facing is that when a user clicks on another user to chat, the previous chat messages are display ...

Learning to retrieve the value from a dynamically generated input tag in a TypeScript file

<div *ngFor="let task of arrayList"> <input id="task.fieldName" *ngIf="task.key === 'Others'" type="text" class="form-control"> </div> When dealing with dynamically created input fields based on a condition, the challenge is ac ...

How to fetch all unique values in MongoDB

In my development setup, I am utilizing React for the frontend and Node.js with MongoDB for the backend. Currently, I am in the process of creating a Select form (drop-down menu) to add new entries to MongoDB. Specifically, for colors, users can select fr ...