Alter the active nav-item's color using Reactjs

Is there a way to dynamically change the color of the navbar text based on the page being browsed?

Check out this sample code

For instance, when on the homepage, I'd like the home icon to appear in blue.

https://i.sstatic.net/uTfwP.png

Take a look at my Menu.js file below:

import React from "react";
import { Link, withRouter } from "react-router-dom";

const Menu = () => {
  return (
    <div className="wrapper">
      <div className="row">
        <nav>
          <Link to="/home">
            <i className="fas fa-home"></i>
          </Link>
          <Link to="/search">
            <i className="fas fa-search"></i>
          </Link>
          <Link to="/notifications">
            <i className="fas fa-bell"></i>
          </Link>
          <Link to="/messages">
            <i className="fas fa-envelope"></i>
          </Link>
          <Link to="/profile">
            <i className="fas fa-user"></i>
          </Link>
          <Link to="/signout">
            <i className="fas fa-sign-out-alt"></i>
          </Link>
        </nav>
      </div>
    </div>
  );
};

export default withRouter(Menu);

I'm struggling to determine the current page location. Can you help?

Answer №1

As stated in the react-router documentation, activeClassName can be utilized to achieve this specific functionality.

For further information, visit this link

Illustration

<NavLink to="/faq" activeClassName="selected">
  FAQs
</NavLink>

Answer №2

Adin's suggestion was to follow this implementation: https://codesandbox.io/s/navbar-active-forked-6nep4

import React from "react";
import { Link, withRouter, NavLink } from "react-router-dom";

const Menu = () => {
  return (
    <div className="wrapper">
      <div className="row">
        <nav>
          <NavLink
            to="/home"
            activeStyle={{
              fontWeight: "bold",
              color: "blue"
            }}
          >
            <i className="fas fa-home"></i>
          </NavLink>
          <Link
            to="/search"
            activeStyle={{
              fontWeight: "bold",
              color: "blue"
            }}
          >
            <i className="fas fa-search"></i>
          </Link>
          <NavLink
            to="/notifications"
            activeStyle={{
              fontWeight: "bold",
              color: "blue"
            }}
          >
            <i className="fas fa-bell"></i>
          </NavLink>
          <NavLink
            to="/messages"
            activeStyle={{
              fontWeight: "bold",
              color: "blue"
            }}
          >
            <i className="fas fa-envelope"></i>
          </NavLink>
          <NavLink
            to="/profile"
            activeStyle={{
              fontWeight: "bold",
              color: "blue"
            }}
          >
            <i className="fas fa-user"></i>
          </NavLink>
          <NavLink
            to="/signout"
            activeStyle={{
              fontWeight: "bold",
              color: "blue"
            }}
          >
            <i className="fas fa-sign-out-alt"></i>
          </NavLink>
        </nav>
      </div>
    </div>
  );
};

export default withRouter(Menu);

Answer №3

I encountered a similar issue while working with the NavLink component. There is a property called activeClassName which can detect when the NavLinkis active and apply the specified style.

For example:

<NavLink to="/faq" activeClassName="selected">
  FAQs
</NavLink>

For more information, visit HERE

Answer №4

To achieve this, utilize the history props method in your code:

import { useHistory } from 'react-router';

import { useHistory } from 'react-router';

var history = useHistory();

if (history.location.pathname == '<your route address>') {
   //insert your specific code here
}

Answer №5

Explore the React Router Documentation

When it comes to history objects, they usually come with the following properties and methods: location - (object) Represents the current location. May contain the following properties: pathname - (string) Indicates the path of the URL

Check out the updated CodeSandbox example through this link

import React from "react";
import { Link, withRouter } from "react-router-dom";

const activeTab = (history, path) => {
  if (history.location.pathname === path) {
    return { color: "#1fa2f1" };
  }
};

const Menu = ({ history }) => {
  return (
    <div className="wrapper">
      <div className="row">
        <nav>
          <Link style={activeTab(history, "/")} to="/home">
            <i className="fas fa-home"></i>
          </Link>
          <Link style={activeTab(history, "/search")} to="/search">
            <i className="fas fa-search"></i>
          </Link>
          <Link
            style={activeTab(history, "/notifications")}
            to="/notifications"
          >
            <i className="fas fa-bell"></i>
          </Link>
          <Link style={activeTab(history, "/messages")} to="/messages">
            <i className="fas fa-envelope"></i>
          </Link>
          <Link  style={activeTab(history, "/profile")} to="/profile">
            <i className="fas fa-user"></i>
          </Link>
          <Link style={activeTab(history, "/signout")}to="/signout">
            <i className="fas fa-sign-out-alt"></i>
          </Link>
        </nav>
      </div>
    </div>
  );
};

export default withRouter(Menu);

Edit:

An interesting benefit of using history instead of NavLink is that NavLink does not support nested routes while history does.

For instance:

"/profile/yogeshdecodes" - Navlink would activate this route.

"/profile/yogeshdecodes" - history wouldn't activate this route because history requires an exact match for activation.

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

Adding a text stroke to the <input type="text"/> element

    Can anyone provide a solution for implementing text stroke in <input type="text"/> that works across all major browsers (Firefox, Google Chrome, Safari, Opera, IE7+)? Is there any method using CSS 2.1 or jQuery to achieve this effect? ...

What is the best way to retrieve multiple elements by class and change their innerHTML?

Encountering an issue with calling multiple elements of the same class using .innerhtml. Here is the URL I am dealing with: When running the following code in Chrome console, this is the output: document.getElementsByClassName('a-size-small a-color- ...

The switch statement is not functioning properly when the button is pressed

I am trying to trigger an alert inside a switch statement when I click a button, but for some reason, it is not working. Even if I simply have an alert in the previous function, there is no output on my website. What could be causing this issue? Here is ...

`Cannot Get jQuery ScrollTop Function to Work for 2nd Element`

Having trouble with an issue. Let me explain. I implemented a scrollTop Jquery on page load that scrolls down after a delay to prompt user action. However, I'm facing a problem where another scrollTop doesn't work after clicking buttons "#b3,#b3 ...

Autocomplete like Google with arrow key functionality

I have developed a basic search engine that retrieves data from a MySQL database using the PHP "LIKE" function (code provided below). Everything is functioning correctly, but I would like to enhance it so that users can navigate search results with arrow k ...

What is the best way to customize the MenuProps of Material UI Select component using createTheme?

I'm trying to update the dropdown menu style of my Material UI Select component using createTheme, but I'm having trouble getting it to work. https://i.sstatic.net/zpVjW.png Here is the code I have so far. Can you spot what might be causing the ...

Using useEffect is not working for me to retrieve data from the API

I am currently working on implementing a tutorial from freecodecamp. The tutorial involves creating a simple react-node app. However, I am encountering an issue where I am unable to retrieve data from the API, and I am seeing the following error in my brow ...

Enhancing JSX Component with Transition Effect in React

Is there a way to incorporate a transition effect when the button is clicked within this React component? Since the code modifies the JSX content instead of the className, traditional CSS transitions may not work. How can I implement a smooth transition ...

"Enhancing button design with an adjacent image - the step-by

I am having an issue with my hover dropdown menu where the image is not displaying properly in the main button. When I hover over the user12345 button, the image appears on the left side just before the hover shadow. Below is the code snippet for the dropd ...

The page keeps refreshing repeatedly

Can someone help me troubleshoot this url modification script? var currentPath = window.location.href currentPath=currentPath.replace(/&amp;/g, "&"); window.location.href=path; It seems like the page keeps reloading endlessly... Any sugg ...

What is preventing it from adhering entirely to the top when using position: fixed?

body { padding: 10px; } .content { background: blue; height: 200px; width: 100px; position: absolute; } <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta name="viewport" conten ...

json evaluation causing an issue

When trying to use eval for the JSON below, I am encountering a syntax error with the message: Expected ']'. I am unsure of what is missing in my code. Here is my JavaScript statement: eval('var jsonResponse = ('+response+')' ...

What steps can I take to ensure this fading divider is responsive across all devices?

My current divider element is styled with CSS properties as follows: .divider { height: 2px; background: black; background: -webkit-gradient(radial, 50% 50%, 0, 50% 50%, 350, from(#000), to(#fff)); } I have two questions regarding this design. First ...

Having trouble with Vue 3 Composition API's Provide/Inject feature in Single File Components?

I am currently developing a VueJS 3 library using the Composition API. I have implemented Provide/Inject as outlined in the documentation. However, I am encountering an issue where the property in the child component remains undefined, leading to the follo ...

``The component in React crashes due to a disabled water filter

My react component crashes after adding an SWR data fetch. Interestingly, if I comment it out the component works fine. Upon uncommenting line const { data } = useSWR(`/api/views/${slug}`, fetcher), I encounter the following error: Error: Element type is i ...

Guide to including user-defined headers in Angular's httpRequest

I am attempting to make an http get() request by passing some values in headers. I am currently updating the headers as follows: import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core' ...

Develop a series of sequential tests for the playwright to execute

Can someone assist me with my code? I am attempting to write a test in Playwright that navigates to the forgot password page, creates a new password, and then tries to log in using that new password. However, I am encountering an issue with retrieving the ...

Record collection of elements - JavaScript Angular

I am facing an issue with my page code. The code contains a list of items and I need to extract the values of Test, Application, Success, Error from these items. However, when I try to write this data to a file, it returns [object, Object]. Can someone ple ...

Choose the tag and class then retrieve the custom attribute

I'm currently attempting to retrieve a specialized attribute utilizing jquery and subsequently choose it, nevertheless I am encountering some difficulties with the process Below is the jquery code I have implemented to access the value var stockId = ...

Transitioning the color of links in Firefox causes flickering when switching between the hover and visited state

I have been working on testing this code snippet in Firefox 49.0 on Linux Mint: a{ font-size:50px; color:gray; font-weight:1000; transition:color 1s; } a:hover{ color:black; } a:visited{ color:lightgray; } <a href="">VISITED LINK</a>&l ...