The NavLink in ReactJS is currently active

I am looking to understand how I can manage the className of a Navlink in React so that when the current path is X, the NavLink has the active class. In the past, I have accomplished this using Laravel and simple bootstrap, but I am unsure of how to achieve the same result with React and Reactstrap.

Example in Laravel:

<a href="{!!URL::to('link1')!!}" class="{{Request::is('link1') ? 'activeMenu' : '' }} >Link1</a>

My code in ReactJS:

  <Nav className="navbar-logged">
    <NavItem>
      <NavLink className="nav-link-gdc" href="/">HOME</NavLink>
      <NavLink className="nav-link-gdc" href="#">LINK1</NavLink>
      <NavLink className="nav-link-gdc" href="#">LINK2</NavLink>
      <NavLink className="nav-link-gdc" href="#">LINK3</NavLink>
      <NavLink className="nav-link-gdc" href="#">LINK4</NavLink>
    </NavItem>
  </Nav>

Answer №1

When utilizing react-router

To specify the path, use the to argument instead of href. For example:

`<NavLink className="nav-link-gdc" to="/">HOME</NavLink>`

This will automatically apply the active class. Refer to the documentation for NavLink

If the NavLink is from reactstrap

You may need to implement some router logic to mark the nav link as active. If you do not require changing the URLs in the address bar, consider following this answer on Stack Overflow

Answer №2

Absolutely, we have the ability to manage the class name of the NavLink element:

 const pathName = this.props.history.location.pathname;
 <NavLink to='/pathNameHome' className='header__route--link'
    activeClassName={pathName === '/home || pathName === '/dashborad' ? 'header__route--active' : ''} >

In the provided code snippet, the variable 'pathName' is extracted from the historical location. If you wish to add a condition based on 'pathName', you can accomplish that with {pathName === '/home || pathName === '/dashborad' ? 'header__route--active' : ''}. Within this segment, we are comparing the paths. Alternatively, if you want, you can directly set activeClassName= 'header__route--active'. As a result, once the path is chosen, the class name 'header__route--active' will be applied; otherwise, the default class name header__route--link will be active.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for conducting a simultaneous test on several devices

Struggling to execute a single test script on multiple devices, regardless of efforts. There is one test apk and script obtained from a website as a sample. The script locates a textbox in the application, enters "Hello World!" into it, then completes the ...

Store the user's link for future reference and quickly navigate to the TransferPage in 3 seconds. Then, return

After a user clicks on any button, they will be redirected to the Transfer Page for 3 seconds. Then, they will automatically return to the link they originally clicked on. Schematic: https://i.sstatic.net/dU30F.png HTML: https://i.sstatic.net/UOldi.p ...

Fluid overlap of divs in Bootstrap framework

I am currently in the process of making style adjustments to a website at One specific change I've made is adding a top bar image. However, I've encountered an issue where the top bar graphic overlaps the navigation when the page is resized too ...

checkbox revision

I'm attempting to update some text indicating whether or not a checkbox is checked. The issue is that when the checkbox is checked, the textbox disappears and the text takes its place. <form name="myForm" id="myForm"> <input type="checkb ...

Is there a way for me to extract text from a leaflet popup in order to generate the complete URL for an AJAX request?

When text within a popup is clicked, I want to trigger an ajax call. The content in the leaflet popup has been set previously by another ajax call. Below is the JavaScript code for both ajax calls: $("#button").click(function() { var name = document. ...

Troubleshooting: Issue with sending JSON data to front-end alongside HTML in Django

Here is the code snippet in question: import json class UserPageView(TemplateView): def get(self, request, *args, **kwargs): obj = User.objects.get(pk=17).username return TemplateResponse(request, template="user.html", context={' ...

Having trouble with Node.js child_process.exec when the command doesn't return any output?

Recently encountered an issue while using child_process.exec in nodejs. The problem occurs when the command returns nothing. Here is what I did: const {exec} = require('child_process'); const cmd = `ps -ef | grep -v grep | grep abc123.py`; exec ...

Verify whether the combined total of two elements sharing the same identifier is less than zero

I am working with two 2D arrays: illustration arr1 = [['2001-01-01', 100], ['2001-01-02', 105],...] arr2 = [['2001-01-01', 100], ['2001-01-02', 120],...] query I want to determine if subtracting any of the [i][ ...

Implementing the migration of a route DTO object in NestJS

Utilizing NestJS for my application, there have been some modifications to the DTO objects that need to be received in the controller. Since the client side consists of a mobile app and users cannot be compelled to update their version, I may receive DTO o ...

Guide on dynamically loading a template in CKEDITOR using ajax

I have a database table where I store my templates in HTML format. I am trying to retrieve a specific template using AJAX. Below is the code I am using: HTML Section <div class="form-group"> <label>Select Template: <span class="text-i ...

I'm looking to convert this typescript function to return an array with strong typing instead of just a plain string[]

I am currently in the process of converting a JavaScript function to TypeScript. Originally, I believed that the type of the variable hi would be ('s'|'bb')[], but it turned out to be string[]. Is there a way for TypeScript to automatic ...

Using JSON data to populate an HTML page

I'm currently working on a project that involves creating a "Twitter" page. The idea is to utilize the JSON file available at to display some of its content. However, I'm facing an issue where my page only shows the table headers and nothing els ...

Sending information (prop) from _app.js to getServerSideProps in a page on the most up-to-date version of NextJS

I have a unique custom _app.js that I created: const CustomLayout = ({ children }) => (children); const myApp = ({ Component, pageProps }) => { pageProps.url = 'another url'; return ( <CustomLayout> <Co ...

Expanding ReasonReact by inheriting the Nextjs App component (pages/_app.js)

Implementing the React Context API in my Nextjs app using ReasonReact has proven to be a challenge due to the bucklescript compiler's approach to inferring module names. In order to make the context available throughout the entire tree, I must inherit ...

In AngularJS, I was attempting to display array indexes in reverse order. Can anyone provide guidance on how to achieve this?

<tr ng-repeat="qualityalert in qualityalerts" current="$parent.start;$parent.start=$parent.start+(qualityalerts.length);"> <td class="v-middle">{{current + $index}}</td> </tr> Important: I was talking about this specific code snipp ...

Should I use the item-text property or another property in v-autocomplete for Vuetify search?

I have a to-do list that consists of an array of objects with properties (id, title, description). I want to display the title in the v-autocomplete, but when I search for a word, it works fine. However, what I actually want is to search for either the des ...

Error encountered with the Angular 2 routing system

Currently, I am facing an issue with my Angular 2 router module. Whenever I try to access the link /city, I encounter an error message saying 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet Error: Cannot activat ...

I'm having trouble getting my jQuery click handler to work

Here is the HTML content within my Sharepoint 2010 Web Part project: <html> <h1>Travel Form Assistance</h1> <div id="preTravel" name="preTravel"> <h2>Pre Travel</h2> <img id="imgPreTravel" name="imgPreTra ...

Understanding Pass by Reference within Objects through Extend in Javascript with underscore.js Library

When working with Javascript and using the extend function in the underscore.js library, I am curious about what happens in relation to memory. Consider this example: var obj = {hello: [2]}; var obj2 = {hola: [4]}; _.extend(obj, obj2) obj2.hola = 5; conso ...

What is the best way to save my photo on the server?

Currently, I am developing an application using Phonegap that is specific for Android, iOS, and Windows phone platforms. As part of the app functionality, I am utilizing the Camera API to capture images on the user's device. However, at the moment, th ...