⊗jsrtPmRtAL 42 of 47 menu

Highlighting Active Link in React Router

Let's say we've added several products to our app and are viewing each product. How do we know which product page we're on? Let's highlight that product in the list, for example, in bold and brown, and if the link is still loading, in gray.

First, go to the main page, add 4 products to the list and enter data for each of them. Give them any names.

The NavLink component will help us to highlight the active link. It is a subtype of the Link component that knows about the state of the data. It is usually used when creating a navigation menu.

Let's open root.jsx and import NavLink (don't forget to remove the import Link, otherwise React might complain, since we're not using it anymore):

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

Then in the layout we replace the Link component with NavLink:

<NavLink key={product.id} to={`products/${product.id}`}> {product.name ? product.name : <i>unnamed</i>} </NavLink>

And we'll add the className props to it, and also use conditional logic. If the page has loaded, the link will go into the active state, if it's loading, then into the loading state, but if nothing happens, it will remain the same. Depending on this, the link class will change:

<NavLink key={product.id} to={`products/${product.id}`} className={({ isActive, isPending }) => isActive ? 'active' : isPending ? 'loading' : '' } > {product.name ? product.name : <i>Unnamed</i>} </NavLink>

All we have left to do is add styles for the active and loading classes to our css file:

a.active { font-weight: bold; color: brown; } a.loading { color: gray; }

Done! Now click on the products in the list.

Take the application you created in the assignments for the previous lessons. Using the lesson materials, implement in it the selection of an active link for the list of students so that it is clear which student's data the user is currently viewing.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline