I'm looking to personalize the appearance of a selected tab in Material-UI using the tab component. How can I achieve this?

I am currently working on incorporating the Material-ui Tab component into my React application. You can find more information about the Tab component here: https://material-ui.com/api/tabs/. Here is how I have set up my Tab bar:

  <AppBar position="static">
    <Tabs
      classes={classes}
      value={value}
      variant="fullWidth"
      centered
      onChange={handleChange}
      aria-label="volunteer dashboard tabs"
>
      <Tab label={proposedLabel} {...a11yProps(2)} />
      <Tab label={planningLabel} {...a11yProps(1)} />
      <Tab label={inProgressLabel} {...a11yProps(0)} />
      <Tab label={completedLabel} {...a11yProps(3)} />
    </Tabs>
  </AppBar>

My question pertains to customizing the style of a selected tab. The documentation mentions the "indicator" class, and I have applied the following styles:

  root2: {
    width: "100%",
    flexGrow: 1,
    backgroundColor: theme.palette.background.paper,
  },
  root3: {
    paddingRight: theme.spacing(1),
    flexGrow: 1,
    width: "100%",
  },
  viewButtons: {
    marginTop: theme.spacing(2),
    marginBottom: theme.spacing(1),
  },
  indicator: {
    border: 0,
    borderBottom: "2px solid",
    "&:hover": {
      border: 0,
      borderBottom: "2px solid",
    },
  }

Unfortunately, the indicator class does not seem to be taking effect. Can anyone provide insight on the correct class to use in order to properly style a selected tab?

Answer №1

The active indicator is actually a component of the tab element, not the tabs themselves. Look inside and you will find a selected prop (which will translate to .Mui-selected).

To style this, make use of createMuiTheme along with MuiThemeProvider:

const theme = createMuiTheme({
  overrides: {
    MuiTab: {
      root: {
        "&.Mui-selected": {
          background: "red"
        }
      }
    }
  }
});

For a functional illustration, refer to this example: https://codesandbox.io/s/mui-theme-style-selected-tab-pe03k?file=/demo.js

Answer №2

It seems like you are looking to customize the appearance of the tab indicator, specifically the border bottom. I encountered a similar issue and managed to find a workaround. While this solution may be considered a hack, it does get the job done. You can achieve the desired effect by setting the indicator background to transparent and applying styles to its inner div as shown below:

indicator: {
    backgroundColor: 'transparent',
    '& > div': {
        width: '100%',
        backgroundColor: theme.palette.primary.main,
        '&:hover': {
            backgroundColor: theme.palette.secondary.main,
        },
    },
},

The hover effect will only trigger when hovering on the indicator itself. If you wish to change the indicator color when hovering over the tab, you will need to apply the styles to the root element instead.

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

I'm having trouble with axios.get when trying to search for a product by name

server-side const ProductListFilter = async (req, res) => { try { const productList = await productModel.find(req.query).collation({ locale: "en", strength: 2 }); return res .status(201) .send({ status: true, ...

I have successfully installed several libraries using the same method, but for some reason React is not recognizing one of them. What could be causing this specific module to not be found?

After running the command "npm install --save -g pondjs", I encountered an error message when executing my code: ./src/Components/Tseries.js Module not found: Can't resolve 'pondjs' in '/Users/<ME>/Google Drive/code/React/project ...

Converting an array of objects into a flat array of objects with Javascript

My data array requires conversion to a flattened array returning new header and data. For instance, the first object contains a name with three data points: "title, first, last." The desired output is: From : { gender: 'male', name: { ...

Displaying a portion of a React functional component once an asynchronous function call has been successfully executed

I am currently using material-ui within a React function component and have implemented its Autocomplete feature. I have customized it so that when the text in the input field changes, I expect the component to display new search results. callAPI("xyz") I ...

Collaborate on sessions across Next.js and React applications

I manage a scenario where I have a Next application utilizing Keycloak for authentication via NextAuth, and another React application also secured by Keycloak using the official keycloak libraries (keycloak-js and react-keycloak/web), both residing within ...

The theming feature in React Material-UI v5 does not seem to be compatible with Story

After spending a few days customizing the primary color and adding two additional colors to the palette, I encountered an issue where the new colors were not being reflected on the button despite properly declaring them. Even wrapping the button under the ...

setting the `checked` property to `false` when converting a controlled checkbox input to an uncontrolled input

Encountering an issue with the following code: The error message states, "A component is changing a controlled input of type checkbox to be uncontrolled." function CheckBox(props) { const id = props.id; const onChange = props.onChange; const f ...

Issue with React Router version 6: displaying an empty page

I am currently grappling with implementing react-router for my react applications. However, I am encountering issues with the routing part as it consistently displays a blank page. Below are snippets of the code from the involved files: index.js import R ...

When using the next/link redirect feature, it is recommended that the page be set to scroll to the top

I'm working on a Next.js website with links in the footer. When I click on one of these links, the page first redirects to the new page with the current position scrolled down and then scrolls back up. However, I want it to default to the top of the p ...

The latest error in the Next.js 13 app directory: React child is not valid (detected: [object Promise])

I am currently utilizing the new app directory feature in Next.js 13. Within my project, I have a page component located at app/page.tsx. This component contains the following code snippet: "use client"; import { useState } from "react" ...

How to Test React Js API Calls with Jest?

I'm currently in the process of writing test cases for my API call function, but I'm encountering difficulties as I am unable to successfully run my tests. Below is the code for the API call function and the corresponding test cases. export async ...

a dilemma involving syntax and database connectivity issues within a node.js environment

Here is the code I am using for connecting to my database in Node.js: var express = require('express') var mongoose = require('mongoose') var cors = require('cors') var morgan = require('morgan') require('dot ...

Dexie is alerting us to a problem with a call that occurs before initialization

When setting up my application, I encountered an error related to the Courses Entity Class being called before initialization in my Dexie Database. Despite checking my code, I couldn't find any issues and there was no documentation available for this ...

Testing the Material UI autocomplete component with Google Maps integration using React Testing Library is an important step in

Recently, I've been working on creating a test for the Material UI autocomplete component. I found a similar implementation in this demo, and attempted to troubleshoot an issue by referring to this query. Unfortunately, I wasn't able to find a so ...

ReactJS is throwing an error, saying that theme.spacing is not a valid function

I encountered an error while working on my 'ReactJS' application. The error message is as follows: TypeError: theme.spacing is not a function (anonymous function) E:/Projects/PortfolioSite/React-Portfolio-Website/react-portfolio-website/src/comp ...

Does anyone have an example of how to integrate Passport Google OAuth2 with Next.js?

If anyone has experience working with passport google oauth2 in a Next.js project, I would appreciate any examples of code you can share. While there are resources available for implementing this in Node.js, the specifics of routes, middleware, and callbac ...

Leveraging a React hook within a Next.js API route

I am looking for a way to expose the data fetched by a React.js hook as a REST endpoint using Next.js. To create a REST endpoint in Next.js, I can easily use the code below in pages/api/index.tsx export default function handler(req: NextApiRequest, res: N ...

Errors arise when module level directives are bundled together, resulting in the 'use client' directive being disregarded and ultimately leading to a JavaScript heap memory overflow

Encountered a pipeline error in my AWS setup that said: "Module level directives cause errors when bundled, 'use client' was ignored causing JavaScript heap out of memory." Seeking a solution to this issue as I am utilizing Vite.js in my React.j ...

Clicking on a ReactJS Modal Window can trigger an action

I am having trouble with my ReactJS Modal Window. Below is the code snippet: import React from 'react'; import './Modal.css'; import Button from 'react-bootstrap/Button'; const Modal = ({ handleClose, show, children }) => ...

Unable to pass on error from Express server to React client app

Background Overview In my project, I've implemented a React component named 'Register.jsx' where users can input their desired username and password. Upon clicking the submit button, this information is transmitted to an Express backend whi ...