Enhance your navigation bar with hover styles in React Router Dom v6

I'm having an issue with my navbar where the active styles are overriding the hover state. I want to maintain my hover state styles even on the active nav link. How can I achieve this?

Here is what's currently happening:

Active nav styles (looks good) https://i.sstatic.net/sSoGN.png

When I hover over the active nav (want the text to be white) https://i.sstatic.net/KZ6b1.png

                <NavLink
                    to="/games"
                    className='nav-link'
                    style={({ isActive }) =>
                        isActive
                            ? {
                                color: '#0E1333',
                                borderBottom: 'solid 2.5px #0E1333',
                                paddingBottom: 2.5
                            }
                            : {}
                    }
                >
                    <img src={require('../../assets/icons/gamesIcon.png')} id='projects-icon' />
                    Games
                </NavLink>

Stylesheet

.nav-link {
  text-decoration: none;
  background-color: white;
  color: #0E1333;
  font-family: 'Gilroy-ExtraBold';
  font-size: 18px;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding-left: 25px;
  padding-right: 25px;
}

.nav-link:hover {
  background-color: #0E1333;
  color: #fff;
}

I've tried...

a.nav-link.active:hover {
  color: white
}

Answer №1

Transfer the "style" logic to the className prop and include the "active" class. The inline style attribute has higher CSS specificity, overriding styles specified in your CSS.

<NavLink
  to="/games"
  className={({ isActive }) =>
    ["nav-link", isActive ? "active" : null]
      .filter(Boolean)
      .join(" ")
  }
>
  <img src={require('../../assets/icons/gamesIcon.png')} id='projects-icon' />
  Games
</NavLink>

CSS

.nav-link {
  text-decoration: none;
  background-color: white;
  color: #0E1333;
  font-family: 'Gilroy-ExtraBold';
  font-size: 18px;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding-left: 25px;
  padding-right: 25px;
}

.nav-link:hover, .active:hover {
  background-color: #0E1333;
  color: #fff;
}

.active {
  color: #0E1333;
  border-bottom: solid 2.5px #0E1333;
  padding-bottom: 2.5rem;
}

Keep in mind that the NavLink component automatically adds an "active" classname by default, simplifying the link logic to:

<NavLink to="/games" className="nav-link">
  <img src={require('../../assets/icons/gamesIcon.png')} id='projects-icon' />
  Games
</NavLink>

https://codesandbox.io/s/quizzical-fire-b17lfl?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.js&theme=dark

Answer №2

There is an issue with the style props in the NavBar component as it is overriding the hover state declarations.

A possible solution would be to remove the style prop and directly declare styles in the external .css file.

<NavLink to="/games" className="nav-link">
  <img src={require("../../assets/icons/gamesIcon.png")} id="projects-icon" />
  Games
</NavLink>;
a.nav-link.active {
    color: #0E1333;
    border-bottom: solid 2.5px #0E1333;
    padding-bottom: 2.5em;
}

a.nav-link.active:hover {
    color: white
}

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

Tips for verifying if a user input aligns with a specific regular expression in a React application

updateModalField = event => { var inputValue = event.target.value; var isBtnDisabled = true; if ( inputValue && /^[A-Za-z]{5}$/i.test(inputValue) ) { isBtnDisabled = false; } this.setState({ ...

Create multiple buttons with uniform width by adjusting padding in CSS

I recently attempted to create buttons using CSS and padding. Here is the HTML code for the buttons: <link rel="stylesheet" type="text/css" href="css/style-login.css" /> <link rel="stylesheet" type="text/css" href="css/font-awesome-4.0.3.css" /& ...

Adjusting the background color of <tr> depending on the number of <tr> elements in the HTML using CSS

When working on my HTML page, I have utilized multiple <tr> tags with different bgcolor values such as: <tr bgcolor="#000000"> <tr bgcolor="#E5F1CC"> <tr bgcolor="#D30A0A"> <tr bgcolor="#656766"> I am aiming to assign unique ...

Looking to Move the Image Up?

I've been experimenting with creating a grid layout where the bottom image will move up until it is 10px away from the image directly above it. However, no matter what I attempt, the spacing seems to be based on the tallest image rather than the one a ...

Progress Bars Styled with CSS Percentages

I need help creating a basic CSS percentage bar. To get started, visit and paste the following code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://w ...

Navigating the process of transferring a function to a functional component within React

Hey there, I'm fairly new to using React and TypeScript and I am facing a small issue with moving a function from the file App.tsx to a functional component called WordAddingForm.tsx. Any help would be greatly appreciated! Let's start with my Ap ...

There was an issue with retrieving the image URL from the source, causing an error message to display: "

I encountered an error while trying to access my product. Here is the error message https://i.stack.imgur.com/fTmL0.png It seems that the image URL from the sanity database cannot be rendered, even though it worked fine in the tutorial I was following. I ...

Looking to display dropdown menus on a new line along with a text input field using jQuery?

<script type="text/javascript"> var arr = [{ val: 1, text: 'Option 1' }, { val: 2, text: 'Option 2' }]; $(function () { $('a').click(function () { var sel = $('<select>&apo ...

Menu Drop on top of Flash player

A challenge I am currently facing is with my live event site and the list of events displayed in a mouseover menu. The issue arises when the flash streaming player remains in front of the mouseover menu, causing interference across all versions of Interne ...

Error: The module cannot be found. Reason: Unable to resolve '../config' in '/vercel/path0/components'

Encountered an issue while deploying my next.js app through Vercel. The app runs smoothly locally using the 'npm run dev' command. However, when attempting to deploy it via Vercel with a remote GitHub repository, I encountered the following error ...

Adjusting the size of Bootstrap alerts while ensuring the close icon remains correctly positioned

Below is the HTML code snippet I am working with: <div class="row mt-2"> <div class="col-lg-5"> <div id="alertmessages"></div> </div> <div class="col-lg-7"> <div class="btn-group-sm"> ...

Internet Explorer reverts back to default fonts once the webpage has completed loading

I'm encountering a minor problem with a website I'm currently working on. My CSS and web fonts are from Fonts.com, and everything seems fine except in Internet Explorer. Initially, the page displays with the fonts correctly applied, but once the ...

Is it possible to stack one Canvas on top of another?

Right now, I am engaged in a process that involves: creating a canvas and attaching it to a division applying a background image through CSS to that canvas. drawing a hex grid on the canvas placing PNGs on the canvas. animating those PNGs to show "movem ...

What steps can I take to ensure my CSS selector for the element is functioning properly?

Here is an example of some code: <html> <head> <style> .test{ background-color: red; p { background-color: yellow; } } </style> </head> <body> <div class="test"> ...

Floating CSS drop menu with added bottom margin

I have created a simple dropdown CSS menu positioned in the footer with an upwards direction. You can view it here: http://jsfiddle.net/RmTpc/11/ My issue is that I want the opened menu to have some bottom margin from the main list item ("Items"). However ...

Jquery bypasses original stylesheet settings when inline styles are removed

I have a CSS file with various styles defined within it. One style in particular has the property position set to 'fixed', but this only applies to specific combinations of classes. For example: .mystyle.blue { position: fixed; } Here, el ...

Establish a new <section> to serve as a distinct webpage

I have a question about creating multiple <section> elements on a page. I am looking to build an HTML document with several <section> tags, as outlined below. <html> <head> </head> <body> <sectio ...

I just completed my first React app and after uploading it to GitHub, all I see is a blank page when I navigate to the GitHub

Hello, I am currently facing an issue with uploading a React page to GitHub. Initially, I encountered a problem where it only displayed the README file. However, I was able to resolve this by following the deployment guide on the React website. This solv ...

Unable to implement a design on a button during its click event

I successfully implemented a dynamic button in HTML5 and Javascript. The button has a click event assigned to it, so when clicked, its content and background color are supposed to change. However, while the content changes correctly, the background color d ...

How can I create dynamic tabs using Tailwind CSS?

I am looking to create an animated tab using React and Tailwind CSS. Here is the code I have so far: import React from 'react' import clsx from 'clsx' export const Modal = () => { const [theme, setTheme] = React.useState<' ...