active styles using NavLink

by Sai gowtham1min read

It is used to style the active routes so that user knows on which page he or she is currently browsing on the website.

The Link component is used to navigate the different routes on the site. But NavLink is used to add the style attributes to the active routes.

In our routing app, we have three routes which are [home, /users, /contact] Let’s style them using NavLink.

We need to add a new prop called activeClassName to the NavLink component so that it applies that class whenever the route it is active.




import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import {
  BrowserRouter as Router,
} from 'react-router-dom'
import App from './App'
import Users from './users'
import Contact from './contact'
import Notfound from './notfound'

const routing = (
          <NavLink exact activeClassName="active" to="/">            Home
          <NavLink activeClassName="active" to="/users">
          <NavLink activeClassName="active" to="/contact">
      <hr />
        <Route exact path="/" component={App} />
        <Route path="/users" component={Users} />
        <Route path="/contact" component={Contact} />
        <Route component={Notfound} />

ReactDOM.render(routing, document.getElementById('root'))

Now you can see a red color is applied to the active routes.

navlink react router