Home > database >  How to make an active navbar link when it shows its page using react-bootstrap
How to make an active navbar link when it shows its page using react-bootstrap

Time:01-05

I'm using react bootstrap and react in the development of my portfolio app, however, I just need one small detail to add and can't find the right method to do it.

I need to make the link on the navbar switch color depending on the page, for instance if I'm on the home page, "Home" on the navbar should be different in color, and so on.

This is the last thing i need to finalize my code.

if you want to check the whole repository here it is: enter image description here

CodePudding user response:

Import the useLocation hook from React Router then you can make some dynamic classNames:

// ...
import React, { useEffect, useState } from 'react';
// Import useLocation hook
import { Link, useLocation } from 'react-router-dom';

function NavBar() {
  const location = useLocation(); // once ready it returns the 'window.location' object
  const [url, setUrl] = useState(null);
  useEffect(() => {
    setUrl(location.pathname);
  }, [location]);
  // ...
  return (
    // ... Just a dumbed down example:
    <Nav>
      <Link to="/" className={"underline"   (url === "/" ?" active" : "")}>Home</Link>
      <Link to="/projects" className={"underline"   (url === "/projects" ?" active" : "")}>Projects</Link>
      <Link to="/contact" className={"underline"   (url === "/contact" ?" active" : "")}>Contact</Link>
    </Nav>
  );
}

And so on. Do this for each Link and add the path name, and it'll work like expected.

Obviously in your CSS you need to create a class to show the active link, e.g.:

.active {
  color: red;
}

CodePudding user response:

You can use like this.

import React from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';

class NavLink extends React.Component {
    render() {
        var isActive = this.context.router.route.location.pathname === this.props.to;
        var className = isActive ? 'active' : '';

        return(
            <Link className={className} {...this.props}>
                {this.props.children}
            </Link>
        );
    }
}

NavLink.contextTypes = {
    router: PropTypes.object
};

export default NavLink;

And use it as given below in your component:

...
import NavLink from "./nav_link";
.....

<nav>
   <ul className="nav nav-pills pull-right">
      <NavLink to="/">
         <i className="glyphicon glyphicon-home"></i> <span>Home</span>
      </NavLink>
      <NavLink to="about">
         <i className="glyphicon glyphicon-camera"></i> <span>About</span>
      </NavLink>
   </ul>
</nav>
  •  Tags:  
  • Related