Home > AI > Frontend > react-router-dom >

NavLink

Compared to the Link, it can add extra active class to the link.

Example code:

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';
import {BrowserRouter, Switch, Route} from 'react-router-dom'
import { Nav } from './components/Nav';
import { About, Home } from './components/Page';

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <div>
        <Nav />
        <hr />
        <Switch>
          <Route path="/" exact>{Home}</Route>
          <Route path="/about">{About}</Route>
        </Switch>
      </div>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

index.css

body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}


* {
  box-sizing: border-box;
}





.normal {
  background: #ccc;
  color: #000;
}

.active {
  background: #fbfb09;
  font-weight: 600;
  text-transform: uppercase;
}

.address-bar {
  background: #ccc;
  padding: 0.5rem;
  border: 1px solid;
  
}
.address-bar a {
  margin: 0 2px;
  cursor: pointer;
}

.address-bar a url {
    display: inline-block;
    padding: 0.2rem 0.5rem;
    background: #FFF;
    margin-left: 5px;
    width: 60%;
}

components/Nav.js


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


export const Nav = () => {
    return (
      <ul>
        <li>
          <NavLink to="/" className="normal" activeClassName="active" exact>home</NavLink>
        </li>
        <li>
          <NavLink to="/about" className="normal" activeClassName="active" exact>about</NavLink>
        </li>
      </ul>
    );
  };

components/Page.js

export const Page = ({ title }) => (
    <div>
      <h1>{ title }</h1>
      <p>Active navigation link must have a yellow background...</p>
    </div>
  );
export const Home = () => <Page title="Home" />;
export const About = () => <Page title="About" />;

Leave a Reply