Tips for customizing a link element that routes to a React component

App.js:

import './App.css';
import logo from './images/logo.png';
import Home from './components/Home';
import About from './components/About';
import Calculators from './components/Calculators';
import Classes from './components/Classes';
import Riddles from './components/Riddles';
import { useRoutes, BrowserRouter as Router } from 'react-router-dom';

const MenuBar = () => {
  return (
    <header className='App-header'>
    <div className="container">
      <a id="home" className="content-tab" href="/"> Home</a>
      <a id="about" className="content-tab" href="/about"> About</a>
      <a id="calcs" className="content-tab" href="/calculators">  Calculators</a>
      <a id="riddles" className="content-tab" href="/riddles">Riddles</a>
      <a id="classes" className="content-tab" href="/classes">Classes</a>
    </div>
  </header>
  )
}

const App = () => {
  let routes = useRoutes([
    { path: "/", element: <Home /> },
    { path: "about", element: <About /> },
    { path: "classes", element: <Classes />},
    { path: "calculators", element: <Calculators />},
    { path: "riddles", element: <Riddles /> },
    // ...
  ]);
  return routes;
};

function AppWrapper() {
  return (
    <div className="App">
      <MenuBar />
      <Router>
        <App />
      </Router>
    </div>
  );
}

export default AppWrapper;

In order to have the links marked with border-bottom: 1px solid white; when selected, you tried using this CSS rule:

.container a.active {
  border-bottom: 1px solid white;
} 

However, it doesn't seem to work as expected. You're wondering if this could be due to the redirection to different URLs and are considering importing App.css into your Home, About, etc components. Any thoughts on why the styling isn't being applied correctly?

Answer №1

It is recommended to utilize Link or NavLink for applying active styling, rather than using the raw anchor tag <a />. Utilize the function callback for the className prop, which receives an isActive prop.

NavLink

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

const MenuBar = () => {
  const getLinkClassNames = ({ isActive }) => [
    "content-tab",
    isActive ? "active-tab" : null,
  ]
    .filter(Boolean)
    .join(" ");

  return (
    <header className='App-header'>
      <div className="container">
        <NavLink
          id="home"
          className={getLinkClassNames}
          to="/"
        >
          Home
        </NavLink>
        <NavLink
          id="about"
          className={getLinkClassNames}
          to="/about"
        >
          About
        </NavLink>
        <NavLink
          id="calcs"
          className={getLinkClassNames}
          to="/calculators"
        >
          Calculators
        </NavLink>
        <NavLink
          id="riddles"
          className={getLinkClassNames}
          to="/riddles"
        >
          Riddles
        </NavLink>
        <NavLink
          id="classes"
          className={getLinkClassNames}
          to="/classes"
        >
          Classes
        </NavLink>
      </div>
    </header>
  );
}

CSS

.active-tab {
  border-bottom: 1px solid white;
}

If you prefer the v5 syntax, then you can create a custom NavLink component.

import { NavLink as BaseNavLink } from "react-router-dom";

const NavLink = React.forwardRef(
  ({ activeClassName, activeStyle, ...props }, ref) => {
    return (
      <BaseNavLink
        ref={ref}
        {...props}
        className={({ isActive }) =>
          [
            props.className,
            isActive ? activeClassName : null
          ]
            .filter(Boolean)
            .join(" ")
        }
        style={({ isActive }) => ({
          ...props.style,
          ...(isActive ? activeStyle : null)
        })}
      />
    );
  }
);

Usage:

<NavLink
  id="home"
  className="content-tab"
  activeClassName="active-tab"
  to="/"
>
  Home
</NavLink>

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

What is the reason behind opting for ng-style over style in AngularJS for applying CSS formatting?

Recently, I've delved into AngularJS and have been exploring its depths for a few days now. I'm curious about the use of ng-style in styling components within both static and dynamic webpages. Given that we already have the traditional style tag ...

What is the proper way to retrieve this stylesheet and add it to the header of my HTML file?

I want to utilize a style sheet from Wikipedia. However, when I fetch the style sheet and attempt to pass the URL retrieved through AJAX to the head of my HTML document, the URL behaves unexpectedly. Initially, I tried to use the fetched URL directly: var ...

Using Javascript to Conceal Button for Unauthenticated Users

Our website is currently running on an outdated e-commerce CMS platform, which limits my options due to my beginner level skills in JavaScript and jQuery. One specific issue we are facing is the need to hide Prices and Add to Cart buttons for users who ar ...

In React, the goal is to render nested data recursively and retrieve the "name" from a JSON file

How can I extract a list of "name" values from this JSON list? [ { "id": "LIB1", "name": "Library 1", "context": "C1", "children": [ { "id": "SKI1", "name": "SKill 1", ...

After my data rows are filled, I add jQuery and CSS striping animations to enhance their appearance

Before any click, they have this appearance: Clicking on Sales in the business section reveals a drop-down select box. If I click on "Sales" and modify the text area, it will transition to grey. While the grey rows change accordingly, the black rows shoul ...

Having trouble showing table data in Angular

My goal is to showcase data from a table created using Spring-Boot Below is my model.ts: export class Quiz1 { QuestionId?: any; Question?: string; OptionsA?: string; OptionsB?: string; OptionsC?: string; OptionsD?: string;} He ...

Insert a new <tr> element into a dynamic table using PHP and jQuery without the need to refresh the page

I am attempting to dynamically insert a row into an existing table when a button is clicked. The rows in the table are created dynamically based on data retrieved from a PHP script. My approach involves making an ajax call to the insert_tr.php script, whi ...

Is It Possible to Create Flash Content Without Using a SWF File?

Is there a way to embed Flash directly in HTML, rather than linking to an external SWF file? I am looking to send an HTML form via email for the recipient to fill out by opening it in a browser. The final step would involve copying the result to their clip ...

Troubleshooting my HTML5 local storage issues for optimal functionality

I've been working on using HTML5's localstorage to save two variables and load them upon page refresh, but I seem to be encountering some issues when trying to load the saved items: Variables in question: var cookies = 0; var cursors = 0; Savi ...

Unable to Render Data URI onto HTML5 Canvas

I have been attempting for quite some time and feeling frustrated. I am facing issues with my Data URI image not being able to write to my canvas for reasons unknown .... Here's the code snippet ... function addImage() { var allfiles = $("#postAtta ...

Extracting Object Properties in JavaScript with React

Code: const [obj, setObj] = useState(() => ({ a: valueA, b: valueB, get values() { if (!this.a || !this.b) { return []; } // code... } return [this.a, this.b] }, })); Values update: useEf ...

modify the color of text in a row within a jquery ajax table

Is it possible to change the font color of values in a row based on a condition inside a function? Specifically, if the TotalStudent count exceeds the room capacity, can we add student information to the table with red font color? Below is my attempt using ...

What sets apart adding a row from adding a col-12 in Bootstrap 4?

I have a doubt that I'm trying to clarify, but unfortunately it's not mentioned in the Bootstrap 4 documentation. Can someone explain the difference between these two code snippets? <div class="container"> <div class="row"> < ...

Utilizing JavaScript for manipulating arrays and displaying images

After asking this question previously without a satisfactory solution, I am hoping to provide better clarification. Imagine having an array with 3 items and it lands on 0 - a code is set up to display this in a div. Now, I want the image to be shown righ ...

Can a video or image be displayed in HTML using an absolute path from a disk named E: while the localhost files are located in C:?

I'm attempting to construct a basic webpage utilizing HTML and PHP to display various videos, each video within its own videoplayer. The issue arises when I try to find the videos (they are stored in a folder on my secondary hard drive labeled E:&bso ...

What is the best way to incorporate my Submit function within Formik?

I'm currently working on incorporating my submit function to send form data to my Django API after form validation using Formik. I have attempted to call the function to post the data. Here is how my onSubmit function for Formik appears: const Regist ...

Count the base in MySQL based on the $_SESSION['username']

I am seeking a solution to determine how many times the same username appears in 2 or more tables. The username I need to search for will be selected from $_SESSION['username'] First Table | id | username | date | | 1 | Mart |28-5-13| | 2 ...

How to process response in React using Typescript and Axios?

What is the proper way to set the result of a function in a State variable? const [car, setCars] = useState<ICars[]>([]); useEffect(() =>{ const data = fetchCars(params.cartyp); //The return type of this function is: Promise<AxiosRespo ...

What are some other options to using position: absolute when working within an inline position:relative?

I've been struggling with this problem for some time now and just can't seem to find a solution. The issue involves a series of position: relative spans enclosing text, along with a position: absolute span set to right: 0;. I expected the second ...

Is there a way to eliminate the whitespace beneath the "Brilliant" division?

[Screenshot of white space under div] [1]: https://i.sstatic.net/cO7TV.jpg I'm having trouble figuring out why there is visible white space here. As a coding beginner, I would really appreciate any assistance. I've tried searching for the soluti ...