When a Mui Button is clicked, it changes the color of all tabs instead of just the active

My website footer contains 5 links represented by Mui Buttons with the component set to {Link} in order to transform them into clickable links. Currently, all the buttons are black and change to green when hovered over. However, I want the button color to remain green if it has been clicked. The issue is that the onClick event changes the color of all buttons, not just the active one.

I have tried various solutions, but none have resolved the problem. Any assistance is greatly appreciated!

Attempted solution #1:


const styles = {
    footerLogo: {
     width: '300px',
     height: '57px',
     align: 'center'
    },
    navLink: {
      fontSize: '16px',
      color: 'black',
      "&:hover":{
        color:'green'
      }
    },
    active: {
      color: 'green'
    }
  };

  const navButtons = [
    {
      button: "Services",
      link: "/services",
    },
    {
      button: "Featured Work",
      link: "/work",
    },
    {
      button: "About",
      link: "/about",
    },
    {
      button: "Contact",
      link: "/contact",
    },
  ];

  
  const location = window.location.pathname;

  const currentTab = location === navButtons[0].link ? styles.active : styles.navLink


 
 <Box
       display='flex'
       justifyContent='space-around'
       marginTop='50px'
      >
        {navButtons.map(({button, link, index}) => (
          <Button
              key={index}
              to={link}
              component={Link}
              sx={currentTab}
             
          >
            {button}
          </Button>
        ))}
      </Box>

Attempted solution #2:


const [isClicked, setIsClicked] = useState(false);
  

const handleClick = () => {
    setIsClicked(true)
  }

 <Box
       display='flex'
       justifyContent='space-around'
       marginTop='50px'
      >
        {navButtons.map(({button, link, index}) => (
          <Button
              key={index}
              to={link}
              component={Link}
              onClick={handleClick}
              sx={{
                color : isClicked ? "green" : "black",
                 "&:hover":{
                   color:'green'
                 }
               }}
          >
            {button}
          </Button>
        ))}
      </Box>

Answer №1

const [isButtonClicked, setIsButtonClicked] = useState(false);
  

const handleButtonClick = (buttonIndex) =>{
    setIsButtonClicked(buttonIndex)
  }

 <Box
       display='flex'
       justifyContent='space-around'
       marginTop='50px'
      >
        {navigationButtons.map(({label, targetLink, buttonIndex}) =>(
          <Button
              key={buttonIndex}
              to={targetLink}
              component={Link}
              onClick={()=>handleButtonClick(buttonIndex)}
              sx={{
                color : isButtonClicked === buttonIndex ? "green" : "black",
                 ":hover":{
                   color:'green'
                 }
               }}
          >
            {label}
          </Button>
        ))}
      </Box>

Answer №2

When considering the initial approach, the comparison is consistently between the location and the first navbutton link, which is navButtons[0].link

Regarding the alternative solution, the isClicked state applies to the entire component rather than each individual button. It may be beneficial to include the isClicked property within your navBtn array instead of having a single state for it.

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

Learn how to dynamically update the URL path when a specific tab link is clicked

One challenge I'm facing on my website is with the tabbed navigation for sub sections. The current script checks the URL path and selects a specific tab from the subNav array if it exists. However, switching to another top-level page doesn't upda ...

The value you have assigned, `undefined`, is out of range for the select component in react material-ui

<FormControl size="small" variant="outlined" style={{ width: '100%' }} > <InputLabel>Type</InputLabel> <Select label="type" value={'' || selectValue} onChange={han ...

Having trouble setting the `variant='dense'` for material-ui Toolbar – it remains at a height of 64px no matter what

Implemented a hello world AppBar/Toolbar with the variant='dense' style. import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import registerServiceWorker from './registerServiceWo ...

Positioning of the footer using CSS: A query

What is the best way to position a footer if we know its height? For instance, if the height of the footer is 100px: footer { position:absolute; bottom: 100px; background: red; } If this approach is not recommended, could someone assist m ...

What is the process for configuring environmental variables in webpack?

Currently, I am utilizing nvm, webpack, and yarn to locally run a React application (not a create-react-app application). However, I have encountered an issue where environment variables specified in the terminal session are not being recognized by the nod ...

Is it possible to convert the text.json file into a jQuery animation?

Looking to extract information from text.json and integrate it with my jquery.animation(). My goal is similar to the one demonstrated here. Instead of using "data" attributes like in that example, I want to parse the text based on the "ID" property as a k ...

How can a div be utilized to create a footer with two columns?

Is there a way to design a two-column footer using only divs and no tables? The dimensions of the footer are set at 980px and it needs to include... Copyright 2010 xyz.com (to be placed on the left side) About us | privacy | terms (to be placed on the r ...

Utilize React JS to dynamically render JSON array of images onto a JSX page in React

state = { products: [ { img: "'./images/heartstud.jpg'", name: "Heart Earrings", price: "1.99", total: "3.98", count: 2, description: "Yellow Chimes Crystals from Classic Designer Gold Plated Styl ...

Create a new division directly underneath the bootstrap column

Imagine having a bootstrap table like this: https://i.sstatic.net/kXHiP.jpg Now, if you want to click on a column and open a div with more details below it, is it achievable with CSS or JavaScript? https://i.sstatic.net/HIfkK.jpg I tried using the Metr ...

What could be the reason behind the significant void in the grid I designed?

I'm currently learning how to utilize the grid container and have successfully created a grid with 2 images on top, 2 on the bottom, and one that stretches vertically on the left side. While I have arranged the grid as desired, I am facing an issue wi ...

Angular-Phonegap - The issue with "min-height: 100%" not functioning properly

I am faced with this specific HTML file: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="format-detection" content="telephone=no" /> <!-- NOTE: Make sure to remove the width=d ...

An error occurs when calling useSWR in a function that is neither a React function component nor a custom React Hook function

When using useSWR to fetch data from an endpoint, I encountered the following error (I only want to fetch data onclick) "useSWR is called in function `fetchUsers` that is neither a React function component nor a custom React Hook function" Error ...

"Initiate React app with specific port number using the Command Line Interface

I'm trying to launch my react server on Linux CLI with a specific port number without modifying the package.json script. I want the ability to run multiple react instances on different ports via CLI. I've come across suggestions like npm start ...

What is the proper error type to use in the useRouteError() function in react-router-dom?

In my React project, I am utilizing the useRouteError() hook provided by react-router-dom to handle any errors that may arise during routing. However, I'm uncertain about the correct type for the error object returned by this hook. Currently, I have ...

Is there a problem with the useEffect function that is causing the page to refresh every 4 seconds?

Experiencing an unusual issue with my Footer component. The useEffect function seems to be triggering a re-render of the entire page and component every 4 seconds, instead of just updating the specific element. I'm not sure where I've gone wrong. ...

Attempting to position the calendar control at the center in Visual Studio using C#

I'm currently working in Visual Studio using C# and I've encountered an issue with centering a Calendar control within a Panel. While I have successfully centered other elements such as radiobuttons, checkboxes, and textboxes in the panel, the t ...

Stop the removal of the CSS content property

When a user enters and re-enters their password, I have a form that checks the strength of the password and displays text accordingly. However, I noticed that if a user makes a mistake and uses the backspace to re-enter the password, the text from data-tex ...

A method for displaying monthly data in a single row

Hey there! I'm currently dealing with a data list stored in an array. The |arraycontains various objects` each with their own properties such as name, created-at, and more. My goal is to display all users who were created within a specific month in on ...

Fade or animate the opacity in jQuery to change the display type to something other than block

I am currently using display: table and display: table-cell to vertically align multiple divs. However, I have encountered an issue when animating the opacity with jQuery using either fadeTo() or fadeIn. The problem is that it always adds inline style di ...

How to minimize the amount of typing needed when specifying grid positions in CSS Grid layout?

(I am currently in the process of upgrading the design of this data entry page from a basic CSS/HTML table layout to something more advanced, utilizing CSS Grid layout). Following common conventions, I have structured it into 12 columns. Each entry field ...