Tips for customizing the appearance of the active item in the navigation bar

Currently, I am developing a project with React.js using HTML, CSS, and JavaScript. My goal is to enhance the visual appeal of the active navigation item in the navbar by adding a white border around it. This way, the border will remain visible while the corresponding page is open.

import React, { useState } from "react";
import { Link } from "react-router-dom";
import "./Navbar.css";
import { navItems } from "./NavItems";
import Dropdown from "./Dropdown";
    
function Navbar() {
  const [dropdown, setDropdown] = useState(false);


  return (
    <>
      <nav className="navbar">
        <ul className="nav-items">
          {navItems.map((item) => {
            if (item.id === "C3") {
              return (
                <li
                  key={item.id}
                  className={item.cName}
                  id={window.location.pathname === item.path? "C10":""}
                  onMouseClick={() => setDropdown(true)}
                  onMouseEnter={() => setDropdown(true)}
                  onMouseLeave={() => setDropdown(false)}
                >
                  <Link to={item.title}>{item.title}</Link>
                  {dropdown && <Dropdown />}
                </li>
              );
            }
            return (
              <li key={item.id} 
              className={item.cName}
              id={window.location.pathname === item.path? "C10":""}
              >
              
                <Link to={item.path}>{item.title}</Link>
              </li>
            );
          })}
        </ul>

      </nav>
    </>
  );
}

export default Navbar;

The following is the stylesheet (CSS) used:

  
.nav-item a:hover {
    border: solid 2px white;
  }


#C10{
  border: solid 2px white;
}

I attempted to apply the white border using the CSS code snippet below:

.nav-item a:active {
    border: solid 2px white;
  }

Even after implementing the CSS in both the stylesheet and JavaScript file, the desired effect was not achieved!

id={window.location.pathname === item.path? "C10":""}
#C10{
  border: solid 2px white;
}

Answer №2

According to William, it is recommended to utilize the actual <NavLink/> elements rather than coding plain HTML in React. Nonetheless, you have the option to create a function that applies the active class to the li item when it is selected.

Take a look at this example:

const links = ['https://google.com', 'https://google.be', 'https://google.nl'];
const [active, setActive] = useState(null);

<ul>
  {links.map((link) => (
    <li className="nav-item">
      <a 
        href={`#${link}`} 
        className={`nav-link ${active == link && 'm-active'}`}
        onClick={() => setActive(link)}
      >{link}</a>
    </li>
  ))}
</ul>

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

Converting MultiSelect Array from JavaScript to MySQL

I recently implemented a multiselect feature on the client side: <select name="country" data-placeholder="Choose a Country..." tabindex="2"> <option name="country" value="United States">United States</option> & ...

Tips for retrieving items from <ng-template>:

When the loader is set to false, I am trying to access an element by ID that is located inside the <ng-template>. In the subscribe function, after the loader changes to false and my content is rendered, I attempt to access the 'gif-html' el ...

Chrome Flexbox Hacks: Controlling the Size of Nested Items

How can I ensure that an element nested within a flexbox member in Google Chrome is limited to the size of its container? For example, consider the following scenario: <div style="display:flex; flex-direction:column; height:100vh;"> <div style= ...

What is the reason behind the lack of asynchronous functionality in the mongoose find method

Outdated code utilizing promises I have some legacy code implemented with mongoose that retrieves data from the database. The schema being accessed is AccountViewPermission. Everything works fine as I am using a .then, which essentially turns it into a Pr ...

Center Your Text Vertically on Google Sites

Trying to spice up my Google Sites page, I decided to take matters into my own hands and customize the banner at the bottom of the site. My goal was to create an orange rectangle with two lines of text perfectly centered both horizontally and vertically. D ...

Upgrading from react-router v3 to react-router v4

I am currently facing an issue with transitioning from react-router c3 to react-router v4. I'm struggling to configure it properly. Here is the code that I am importing: import { Route, IndexRoute} from 'react-router'; import { BrowserRout ...

Adding a KendoColorPicker to a column in a Kendo Grid

When using AngularJS with a Kendo UI grid, I need to have a column that includes a colorPicker. Below is the code I have implemented: $scope.thingsOptions = { sortable: "true", scrollable: "true", toolbar: [{ name: "create", text: "Add Profile ...

Diving into Redux brings up the question of whether to use a generic reducer or a

When working with Redux, what is the preferred approach: Creating entity-specific reducers or utilizing a generic reducer based on strict action keying conventions? The former can result in more boilerplate code but offers loose coupling and greater flexib ...

Validation of JSON Failed

Encountered a 400 Bad Request error while attempting to POST an answer using Postman, it appears to be a validator issue. Despite multiple attempts, I have yet to resolve this issue. Below are details of the JSON data being sent in the POST request along w ...

Tips for optimizing HTML and CSS for better browser performance

Just starting to learn HTML, CSS through an online course and currently working on a simple website. The table of contents on my website is centered, but when I resize the browser on my 27-inch iMac, it doesn't stay centered. Any tips? Here's a s ...

Angularjs: The Art of Loading Modules

I am facing an issue while trying to load certain modules. controller1.js: angular.module('LPC') .controller('lista_peliculas_controller', ['$scope', function($scope) { $scope.hola="hola peliculas"; }]); And ap ...

Next.js experiencing hydration error due to dynamic component

Having an issue with my RandomShape component, where it should display a random SVG shape each time the page is reloaded. However, I am encountering a hydration error on the client side. import React from "react"; import shapes, { getRandomShape ...

Can the React Context API in a NextJS application disrupt the Static Site Generator functionality?

My inquiries revolve around nextJS and SSG (static site generator). 1 - My intention is to handle the app state on a global level using react's context api. The information I have suggests that utilizing redux in a next js app disables SSG. Would imp ...

React: Modifying a single input field out of many

Can someone please review this code snippet: https://stackblitz.com/edit/react-koqfzp?file=src/Section.js Whenever I add an item, a random number is also added that I want to be able to edit. This number is displayed in a Material UI Text Field component. ...

Making API calls using JavaScript

I'm struggling with understanding how to approach this problem in javascript. Here is the question along with the details. I would appreciate any assistance. QUERY We have a server backend that provides two endpoints: /GetLocalPressReleases and /Get ...

How come the data I send gets converted to Undefined when working with Tabulator?

I am currently facing an issue with integrating JSON data as search results into my Tabulator. The goal is to display these search results in their respective columns within the Tabulator. Here is the code snippet I have implemented: <body> <div ...

Does Highchart offer support for drilling down into sub-categories?

I want to implement a sub-sub drill down feature in my Chart using the following code snippet. // Create the chart Highcharts.chart('container', { chart: { type: 'column' }, title: { text: 'Highcharts m ...

Can you show me how to extract the html code from a website using python's requests module?

Attempting to retrieve an HTML file from the specified website: Inspecting the source in Google Chrome allows me to obtain the HTML without any difficulty. However, I aim to download multiple pages using Python requests. Unfortunately, when attempting to ...

Issue with VueJS where the data list cannot be accessed from one template in another template

I'm facing an issue with my setup where there is a crash occurring on the v-for construct of the table-component. The error message displayed is: "Property or method "tablesList" is not defined on the instance but referenced during render". Strangely, ...

Program does not display the expected alert message when using if/else statement

I'm grappling with creating a basic program that accomplishes the following: Develop a function declaration named changePowerTotal which accepts: The total current power generated (a numeric value) A generator ID (a number) The new status of ...