Home > Net >  ReactJS Navbar isActive
ReactJS Navbar isActive

Time:10-01

I am trying to have a rotated square sit under the navbar links to indicate which page you are on. The issue I'm having is that the square remains under the "home" page at all times. So if I click on one of the other links (say "About"), the square will appear under "About" but is also still under "Home".

My .css and .jsx for navbar are below...

import {Link, NavLink} from 'react-router-dom'

import './navbar.css'
import {links} from '../data'
import {GoThreeBars} from 'react-icons/go'
import Logo from '../images/example-logo.png'


const Navbar = () => {
  return (
    <nav>
        <div className='container nav__container'>
            <Link to='/' className='logo'>
                <img src={Logo} alt="Nav logo" />
            </Link>
            <ul className='nav__links'>
                {
                    links.map(({name, path}, index) => {
                        return (
                            <li>
                                <NavLink to={path} className={({isActive}) => isActive ? 'active-nav': ''} >{name}</NavLink>
                            </li>
                        )
                    })
                }
            </ul>
            <button className='nav__toggle-btn'>
                <GoThreeBars/>
            </button>
        </div>
    </nav>
  )
}

export default Navbar

CSS...

nav {
    height: 5rem;
    width: 100vw;
    background:var(--color-primary);
    display: grid;
    place-items: center;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99;
}

.nav__toggle-btn {
    display: none;
}

.nav__container {
    height: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
}

.logo {
    width: 5%;
}

.nav__links {
    display: flex;
    gap: 3.5rem;
    align-items: center;
}

.nav__links a {
    transition: var(--transition);
}

.nav__links a:hover {
    color: var(--color-secondary);
}

.active-nav {
    position: relative;
}

.active-nav::after {
    content: '';
    display: block;
    width: 1.2rem;
    height: 1.2rem;
    background: var(--color-primary);
    position: absolute;
    left: calc(50% - 0.6rem);
    transform: rotate(45deg);
    margin-top: 0.9rem;
}

CodePudding user response:

Check out this article.

Specifically this:

Note: we have to add exact props to the nav link with the home route else it will keep the route of the homepage always active.

CodePudding user response:

Just change this line.

<li>
  <NavLink to={path} activeClassName="active-nav" >{name}</NavLink>
</li>
  • Related