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

What is the process for implementing an image as the background instead of a color for each column in a Google chart?

I'm currently working with Google Chart and I have set up a column chart. However, I am looking to display a background image instead of a background color in each column. Is this achievable with Google Chart? If so, how can I accomplish this? If anyo ...

The latest version of React Router Dom, Version 6,

Can you explain the distinction between the Navigate component and the navigate function from the useNavigate() hook? if (therapy !== desiredGroupTherapy || required.includes('admin') && !isAdmin) { const pathname = generatePath(pageR ...

Floating Action Button is not properly attached to its parent container

When developing my React Js app, I decided to utilize the impressive libraries of Material UI v4. One particular component I customized is a Floating Action Button (FAB). The FAB component, illustrated as the red box in the image below, needs to remain p ...

The PubSub feature is not functioning on the client side, however, it is operational on the Graphql playground, an error message displaying "TypeError:

I am currently in the process of developing a Social app utilizing MongoDB, Express, React, Node, Graphql with Apollo. I found a helpful tutorial on freecodecamp which I am following: Link to the video To achieve real-time functionality, I am implementing ...

Create a mock implementation for React testing, utilizing mocked functions

I have created a mock function for firebase authentication by mocking the firebase module in this way: jest.mock("../../lib/api/firebase", () => { return { auth: { createUserWithEmailAndPassword: jest.fn(() => { return { ...

The test execution in Azure Dev Ops using react-scripts seems to be stuck indefinitely

Having trouble getting my React app's tests to stop running in Azure Dev Ops after they finish. The pipeline just hangs indefinitely while the tests have already completed. This is a simple create-react-app with a few tests included. Here is the YAML ...

What is the best approach to dynamically implement useReducer in code?

Take a look at the repository here: https://github.com/charles7771/ugly-code In the 'Options' component, I am facing an issue where I am hardcoding different names for each reducer case instead of dynamically generating them for a form. This app ...

Is it possible to exclusively utilize Bootstrap 4 (excluding react-bootstrap) within my React application?

Is it a bad idea to combine jQuery and React? I came across some information suggesting that they may not work well together. Is this true? ...

Chakra UI Not Displaying Proper Responsiveness on the User Interface

I recently integrated Chakra UI for styling a project on Next.js, and while most components are functioning properly, I am facing challenges with implementing responsive layouts. The styles do not seem to adapt when the screen size is reduced. Here's ...

Using Modernizr to determine the presence of nth-child in a test

I'm attempting to utilize modernizr in order to check for browser support of the :nth-child selector, but I am unsure of how to proceed. I came across this particular example on http://jsfiddle.net/laustdeleuran/3rEVe/ which tests for :last-child. How ...

Having trouble determining the reason for the error: Invalid element type

Exploring with Next.js and Metamask I'm currently experimenting with connecting Next.js to Metamask in a local setting to retrieve addresses and balances of accounts. My initial step involves creating a simple user interface where I can place a "wal ...

Using Reactjs to pass identical props to several components

As a newcomer to reactjs, I'm looking to tidy up my code a bit. I want to know how to use spread attributes for props in the new context api. Both <Today /> and <All /> will be using the same props, which is starting to look messy. Below ...

Using React Hooks: Can you modify the useState hook from a separate .jsx file?

I have a dilemma with two separate components stored in their own files. One of them is meant to be reusable, so I want to keep them separate. However, I need to update a specific hook within the "child" component from the "parent" component. Passing a val ...

The left and right DIVs are not automatically adjusting to the height of the container

I am currently working on a grid layout consisting of 9 div tags, creating 3 rows with 3 divs in each row. Within this grid, each div is supposed to have a background image, except for the second div in the second row. My main challenge lies in getting th ...

Adjust the Weight of a Single Word in H1 CSS

I've been trying to figure out how to achieve the following for a while now. I know I can solve this issue by using different h1 tags and positioning them separately, but I'm curious to find out if there's a way to do it without dividing the ...

How to retrieve the value of an element within a facebox div with jquery

On my page, I have two div tags displayed below. Whenever I try to retrieve the value of the itemName element using $('#itemName').val();, it always returns the value of the element in the first div (which is blank). Is there a way to access the ...

Creating a Navigation Bar using the Flexbox property

As a beginner, I attempted to create a navbar using flex but did not achieve the desired outcome. My goal is to have: Logo Home About Services Contact * { margin: 0; padding: 0; font-family: ...

Dynamic scrolling text for overflowing text display

Here's a scenario I'm facing: Let's say I have three div tags, each 100 pixels wide: <--- DIV WIDTH ---> Text in div 1 Text in div two, it overflows Text in div three <--- DIV WIDTH ---> Currently, I've set the following C ...

What is the best way to remove an item from my online shopping cart using JavaScript?

I am currently developing an online store website. One issue I am facing is deleting items from the cart after a customer completes an order. Below is the array of cart items: const products = [ { id: '0', name: 'Nike Slim Shirt&ap ...

polygon with five or more sides

Can divs be created with shapes such as five or six corners? I am looking to create clickable zones on a map and any alternative methods would be greatly appreciated. ...