Tips for adjusting the color of a <a> tag upon clicking, which remains unchanged until the URL is modified

My goal is to maintain the color of a link when it is clicked. Currently, hovering over the navbar link changes it to greyish, but I want it to remain a different color after clicking on it. I am implementing this using the react-router-dom library for the Link component.

         <nav>
          <ul className="nav-wrapper">
            <li>
              <Link className="link" to="/">
                Home
              </Link>
            </li>
            <li>
              <Link className="link" to="/gallery">
                Gallery
              </Link>
            </li>
            <li>
              <Link className="link" to="/about">
                About
              </Link>
            </li>
          </ul>
        </nav>

I'm unsure about the best approach here - should I use useState to handle the color change upon click, or make the adjustment in CSS? Any suggestions or tips would be greatly appreciated.

Answer №1

(I found your question a bit unclear, so I provided solutions for both scenarios) Alright! Here is how you can change the color of an unvisited link using CSS:

a:link { color: choose your desired color; }

And for changing the color of a visited link in CSS, use this code:

a:visited { color: choose your desired color; }

Check out this example:

a:active {
  color: green;
}
a:visited {
color: purple;
}
<a href="#">This link will have its color changed<a>

If you found a helpful answer, please mark it as such.

Answer №2

react-router-dom comes with an additional feature known as NavLink. With this, you have the option to pass in a special prop called activeClassName, which allows you to apply custom styles to your active link.

For instance:

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

By using this component, you can substitute all of your Link components within your navigation setup.

Answer №3

To activate your element, try using the :active pseudo selector. More details can be found in the documentation.

Answer №4

const [currentTab, setCurrentTab] = useState(0);

        <nav>
          <ul className="nav-wrapper">
            <li>
              <Link className={`link ${currentTab===0?'active':''}`}  to="/" onClick={()=>setCurrentTab(0)}>
                Home
              </Link>
            </li>
            <li>
              <Link className={`link ${currentTab===1?'active':''}`} to="/gallery" onClick={()=>setCurrentTab(1)}>
                Gallery
              </Link>
            </li>
            <li>
              <Link className={`link ${currentTab===2?'active':''}`} to="/about" onClick={()=>setCurrentTab(2)}>
                About
              </Link>
            </li>
          </ul>
        </nav>

You can then style it with CSS,

 li .active{
     color: #your color;
 }

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

I'm encountering an issue in JavaScript while attempting to convert the following string into a JSON object. Can anyone assist in identifying the problem with this string?

How can I correct this string to make it a valid JavaScript JSON object? txt = '{"Categories" : [{"label":"petifores","id":"1"}, {"label":"wedding cake","id":"2"}, {"label":"shapes of cakes","id":"3"}, ...

Transforming BufferGeometry to Geometry using FBXLoader within the Three.js library

Check out my snippet below for loading a .fbx object. It defaults to loading an object as BufferGeometry: const loader = new THREE.FBXLoader(); async function loadFiles(scene, props) { const { files, path, childName, fn } = props; if (index > fi ...

Showing the name of a class

Hello everyone, I have a piece of JavaScript code that generates HTML buttons when the page loads. The button attributes are fetched from a database through an ASP page. Everything is working fine except for displaying the class attribute - it shows as u ...

What is the best way to filter an object in AngularJS based on its properties?

I am faced with the issue of filtering two arrays of objects. Below is an example: $scope.countries = [ {'id' : 1, 'country_name':'India'}, {'id' : 10, 'country_name':'Australia'} ...

How to optimize PHP scripts by using a single MySQL query instead of loops?

Below are the tables I am working with... Locations __________________________________________________________ ID Location Region Country 1 Newmarket Ontario Canada 2 Barrie ...

The WebDriver encountered an error while trying to click on an element

When using Selenium WebDriver, I am facing an issue with selecting an item from a drop-down list. The element I want to click on is labeled as "game club". Despite attempting to select different elements, I keep encountering an error stating that none of ...

What is the best way to ensure that each service call to my controller is completed before proceeding to the next one within a loop in Angular?

Calling an Angular service can be done like this: this.webService.add(id) .subscribe(result => { // perform required actions }, error => { // handle errors }); // Service Definition add(id: number): Observable < any > { retu ...

Is it possible to test a Node CLI tool that is able to read from standard input with

I'm looking for a way to test and verify the different behaviors of stdin.isTTY in my Node CLI tool implementation. In my Node CLI tool, data can be passed either through the terminal or as command line arguments: cli.js #!/usr/bin/env node const ...

The issue with $.parseJSON when encountering double quotes

Could someone please clarify why a JSON string with double quotes can disrupt the functionality of $.parseJSON? This example works: [{"type":"message","content":{"user":"tomasa", "time":"1321722536", "text":"asdasdasd"}}] And so does this one: [{"type" ...

Using React to Render a Component with Local Storage Information

I'm in the process of developing a history list component for a form within a react application and encountering difficulties with local storage. The goal is to display a list of previous user inputs from the local storage data. My current approach i ...

NextJS Module Not Found Errors Arising from Alias Imports

I recently encountered an issue while building a NextJS app where all my import aliases suddenly stopped working. Below is my jsconfig.json configuration: { "compilerOptions": { "baseUrl": ".", "paths&quo ...

The ajaxForm function is failing to execute properly and is not providing any error messages

When trying to use jQuery ajaxForm, I encounter a strange issue. I am attempting to set up a form for file upload with progress percentage tracking. However, my ajaxForm function does not seem to be triggering at all. Below is the code snippet I am usin ...

Styling CSS: Create circular images with dynamic text positioning or resizing on screens larger than 768px

I'm struggling to figure out how to create a circular profile picture on a background image that remains responsive and maintains its position across different screen sizes. Currently, I've been using fixed margin values to adjust the position, ...

Incorporating environment variables into React applications with the help of Vite

I'm currently working on a React project where I need to fetch data from a weather API. However, I've encountered an issue when trying to use the API key stored in a .env file using import.meta.env.VITE_API_KEY;. The error message states that the ...

javascript unable to delete cookie

After conducting extensive research across various articles and links on deleting cookies using JavaScript, I have encountered an issue where the JavaScript code does not seem to be functioning as expected. The code I utilized for setting cookie values usi ...

The text input field is unresponsive and unable to be selected in the mobile layout

I have implemented this <textarea> component within my web application <div class="col-xs-11 lessSpaceBetweenLine"> <textarea class="form-control actionitems" id="actionitems" name="actionitems" rows="2" pl ...

Error in Discord.JS: The function message.author.hasPermission is not recognized

As I was working on creating a new command for my discord.js bot to toggle commands on/off, I ran into some issues. Specifically, when I attempted to use the .hasPermission function, I encountered the following error message: TypeError: message.author.ha ...

Tips on creating a Django query based on user-selected options from a drop-down menu

As a newcomer in an internship role, I have been tasked with creating a website where users can select a program, location, or theme to visualize on a heatmap. To achieve this, I opted to utilize Django. However, I am facing two challenges: Firstly, my M ...

Using the useState hook in React, you can manipulate a deeply nested object by changing its values, adding new fields,

The structure of the nested state object is as follows: key1: { key2: [ { field1: "value", field2: ["value", "value"], field3: [ { ff1: "val", ...

Find the smallest number within an array without relying on the Math function

Could someone assist me in creating a function that finds the lowest number in an array? I've been struggling with this and previous answers on similar questions didn't really help as they presented solutions with unfamiliar code. The current cod ...