Ways to update the background hue of a selected Navigation Tab?

One of the challenges I am facing in my React Project is with the Navigation Tab from material-ui. The issue I encounter is that the active tab should have a background color, and then revert to its original color when not active. However, the transparency applied affects both tabs instead of just the selected active tab. I am looking for a solution to apply a background color only to the active tabs. Any ideas?

Below is the code snippet for the Navigation Tab:

import React from 'react';
import PropTypes from 'prop-types';
import SwipeableViews from 'react-swipeable-views';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';
import ForecastDays from '../forecast/index';

const TabPanel = (props) => {
  const { children, value, index, ...other } = props;

  return (
    <Typography
      component="div"
      role="tabpanel"
      hidden={value !== index}
      id={`full-width-tabpanel-${index}`}
      aria-labelledby={`full-width-tab-${index}`}
      {...other}
    >
      <Box p={3}>{children}</Box>
    </Typography>
  );
}

TabPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.any.isRequired,
  value: PropTypes.any.isRequired,
};

const a11yProps = (index) => {
  return {
    id: `full-width-tab-${index}`,
    'aria-controls': `full-width-tabpanel-${index}`
  };
}

const useStyles = makeStyles(theme => ({
  root: {
    backgroundColor: 'none',
    width: 275,
    marginLeft:72,
    marginTop:40
  },
}));

const DailyHourly = (props) => {
  const classes = useStyles();
  const theme = useTheme();
  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  const handleChangeIndex = index => {
    setValue(index);
  };

  const {forecastdays, hourlyforecast} = props

  return (
    <div className={classes.root}>
      <AppBar   position="static" color="default" style={{background: 'transparent'}}>
        <Tabs
          value={value}
          onChange={handleChange}
          indicatorColor="secondary"
          textColor="primary"
          variant="fullWidth"
          aria-label="full width tabs example"
        >
          <Tab label="Daily" {...a11yProps(0)}
          />
          <Tab label="Hourly" {...a11yProps(1)}
          />
        </Tabs>
      </AppBar>
      <SwipeableViews
        axis={theme.direction === 'rtl' ? 'x-reverse' : 'x'}
        index={value}
        onChangeIndex={handleChangeIndex}
      >
        <TabPanel value={value} index={0} dir={theme.direction}>
            <ForecastDays forecastdays={forecastdays}/>
        </TabPanel>
        <TabPanel value={value} index={1} dir={theme.direction}>
            <ForecastDays hourlyforecast={hourlyforecast}/>
        </TabPanel>
      </SwipeableViews>
    </div>
  );
}

export default DailyHourly

Please see the images below for reference. Any recommendations are greatly appreciated. Thank you!

https://i.stack.imgur.com/Tg7kRS.jpg https://i.stack.imgur.com/nxCfN.jpg

Answer №1

To dynamically add a class based on the current active tab value, you can use something similar to the code snippet below. If the number of tabs is unknown beforehand, you may need to create an additional function.

 <Tab className={value === 0 ? classes.active : ""} label="Daily" {...a11yProps(0)}
  />
  <Tab className={value === 1 ? classes.active : ""} label="Hourly" {...a11yProps(1)}
  />

You can view and edit the code in this CodeSandbox - https://codesandbox.io/s/pedantic-ives-t7sir

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

Ways to create space around Navbar MUI for a more balanced design

Currently, I am working on designing a navigation bar using MUI. My goal is to create a navbar with some space on both sides similar to the one seen on If you take a look at Stackoverflow's navbar, you will notice that it also has space on either sid ...

Leverage async/await within your React component

Do you think it's a good idea to directly use async/await in a React component and then store the result in the Redux store? Here's an example: class User extends Component { render() { return <div>{this.props.user.name}</d ...

Once the image is loaded, cropped, and displayed on the canvas, what is the best way to implement image rotation functionality for the user before converting it to base64?

My process involves cropping images to a square shape and drawing them onto a canvas. if(img.height >= img.width) { ctx.drawImage(img, 0, 0, 110, 110 * img.height / img.width); } else { ctx.drawImage(img, 0 , 0, 110 * img.width ...

Bracket notation accessor cannot be utilized with React aliases

Can someone help me figure out how to create a tabbed-page using the alias feature? I've noticed that JSX doesn't allow object bracket-accessors. Is there an alternative method I could use, considering that the dot-notation would render the alias ...

Can someone guide me on how to customize the CSS of a fab element in Onsen UI?

I've been struggling to change the background color or border of the onsen fab element. I'm working with angular 2 and onsen v2. Even after trying the !important rule, my CSS doesn't seem to take effect unless I disable the fabs default styl ...

The responsive menu refuses to appear

my code is located below Link to my CodePen project I'm specifically focusing on the mobile view of the website. Please resize your screen until you see the layout that I'm referring to. I suspect there might be an issue with my JavaScript cod ...

Elements on the left side are not properly aligned

I've successfully coded the head banner and news containers below the header. However, I'm facing an issue with my left menus: Instead of aligning properly with the header and news containers, they are overlapping them. Here is the HTML Code: ...

Explore the world of threejs with a sphere adorned with cube bumps

Currently, I am navigating through the internet in search of a solution for my problem. The example I came across is quite impressive, take a look: . My dilemma lies in converting these squares into CSS cubes while ensuring that they do not get cut off by ...

Issues with Bootstrap-slider.js functionality

I'm having trouble getting the bootstrap-slider.js library from to function correctly. All I see are textboxes instead of the slider components. You can view an example at I have verified that the CSS and JS files are pointing to the correct direc ...

Learn the method to retrieve data from a row by clicking on a <td> element

Within the Users.jsx file displayed below, I am using the userList array to populate a table with data. A click listener has been set up in a table data cell element, and my goal is for the Trigger function to be triggered with the information of the row t ...

What steps should I take to deploy my React.js updates on a custom domain?

After completing my website using React.js, I realized that I needed to make one final small edit. However, when I ran firebase deploy, the changes were only deploying to the default hosting URL provided by Firebase, not to my custom domain which is alread ...

an illustration of a shopping cart feature using react-redux

Just starting out with react and react-redux, I'm currently diving into the redux example featuring a Shopping-cart. You can find the example here I have a couple of questions: In containers/ProductsContainer.js, the connect function is passing { a ...

Create dynamic Bootstrap 4 menus featuring three levels of navigation - the initial dropdown sub-menu may not display any selectable options

Using Bootstrap 4 and jQuery 2.2.4, I've created a navbar with three layers of menus, comprising two levels of drop-downs from the top-most level. Everything works smoothly except for a glitch on mobile devices. The menu collapses to the hamburger ic ...

The variable keycloak.authenticated remains false in the @react-keycloak/web library even after a user has successfully logged in

In my current project, I have a simple react app and I am looking to integrate keycloak authentication into its pages. The versions I am using are as follows: react v18 keycloak 18.0.0 (with quarkus) react-keycloak/web: 3.4.0 keycloak-js: 20.0.3 react-rou ...

The pure css overlay does not display correctly on Chrome

Could you take a look at the link provided below (just widen the result window a bit) and let me know why there are white lines on top and on the sides of the boxes when the hover overlay is fully loaded? Even when I use a background image for those divs, ...

Tips for toggling the visibility of a <div> element with a click event, even when there is already a click event assigned

No matter what I try, nothing seems to be working for me. I'm looking to hide the <div id="disqus_thread"> at first and then reveal it when I click on the link "commenting", after the comments have loaded. This particular link is located at the ...

Why does my jQuery IMG center script not work in Chrome and Safari, but it works perfectly in IE?

I am experiencing an issue with centering the thumbnails of products on my e-commerce website. Despite successful centering in IE, FF, and Opera, Chrome and Safari are not aligning the thumbnails properly – they remain at the top of the div instead of be ...

Using Flexbox CSS to Expand a Box According to its Content Size, Without Impacting Adjacent Rows

Is there a way to make the bottom-most row (highlighted in yellow) expand downward to fill available space? Check out this link for reference: https://jsfiddle.net/darrengates/oucvnfke/ I initially thought using: flex: auto; would solve the issue. Whil ...

"Exploring the features of next-auth server-side implementation in the latest version of Next.js,

Is it possible to utilize next-auth in a Next.js 14 application router to access user sessions and display page responses using SSR? If so, what steps need to be taken? ...

Ensure two CSS components occupy the entirety of their container, positioned next to each other, with margin spaces between

I am looking to make two elements take up a precise percentage of the parent's width, while also including margins between them. Here is my current setup: <div class='wrap'> <div class='element'>HELLO</div>< ...