简体   繁体   中英

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

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: https://github.com/awadbilal/portfolio

This is my navbar code:

import React from "react";
import { Link } from "react-router-dom";
import { Container, Navbar, Nav, NavDropdown } from "react-bootstrap";
import { useTranslation } from "react-i18next";
import "./style.css";

function NavBar() {
  const { t } = useTranslation();
  // const { t, i18n } = useTranslation();

  // const changeLanguage = () => {
  //   if (i18n.language === "en") i18n.changeLanguage("ar");
  //   else i18n.changeLanguage("en");
  // };

  return (
    <>
      <Navbar className="navBarSection mt-3" collapseOnSelect expand="lg">
        <Container>
          <Navbar.Toggle aria-controls="responsive-navbar-nav" />
          <Navbar.Collapse id="responsive-navbar-nav">
            <Nav className="me-auto pt-3 pb-3">
              <Nav.Link eventKey={1}>
                <Link to="/" className="underline">{t("nav.home")}</Link>
              </Nav.Link>
              <NavDropdown.Divider />
              <Nav.Link eventKey={2}>
                <Link to="/works" className="underline">{t("nav.works")}</Link>
              </Nav.Link>
              <NavDropdown.Divider />
              <Nav.Link eventKey={3}>
                <Link to="/education" className="underline">{t("nav.education")}</Link>
              </Nav.Link>
              <NavDropdown.Divider />
              <Nav.Link eventKey={4}>
                <Link to="/contact" className="underline">{t("nav.contact")}</Link>
              </Nav.Link>
            </Nav>
          </Navbar.Collapse>
          {/* <div className="languageButton" onClick={changeLanguage}>
            {i18n.language === "en" ? "AR" : "EN"}
          </div> */}
        </Container>
      </Navbar>
    </>
  );
}

export default NavBar;

And here is how it should look:

在此处输入图像描述

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, eg:

.active {
  color: red;
}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM