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

When updating packages locally, NPM may throw an error but it still permits updating packages globally

https://i.stack.imgur.com/k6pkY.png When attempting to update packages locally to their most recent version, npm displays an error. However, updating them globally is possible. What is the reason for this and how can the ERESOLVE error be resolved in ord ...

Integrate Django template tags within React components using Gatsby's Helmet package

I need to include a Django tag within the head section so that the template can render dynamic metatags server-side. What I am aiming to accomplish is: {% block metatags %} <meta name="description" content="{{ metatags.description }}&qu ...

Solution not provided for limiting the maximum length in Material UI Textfield

I attempted to set the max length attribute of a TextField in Material-Ui, but couldn't find any property that worked. I also tried using the code below, but it still didn't work: <TextField label="Amazon Login" name=" ...

JavaScript - turn off online connectivity

Is there a way to test my website for offline use by disabling connectivity on the bootstrap before anything loads, so that all data will be loaded from cache? I have tried various offline libraries such as this one, but I haven't found a way to prog ...

What is the best way to organize angularjs controllers and directives within one another?

When I structure my controllers like this: <body ng-app="app" ng-controller="ctrl"> <div ng-controller="app-get"> <app-get></app-get> </div> <div ng-controller="app-post"> <app-post">& ...

When converting a .ts file to a .js file using the webpack command, lengthy comments are automatically appended at the end of

As a backend developer, I recently delved into UI technologies and experimented with converting TypeScript files (.ts) to JavaScript files (.js) using the webpack command. While the conversion works well, the generated .js file includes lengthy comments at ...

Using canvas transformation changes the way drawImage is applied

I have been working on a game as a hobby and you can find it at . I have managed to get most aspects of the game working well, such as transformation, selection, movement, and objects. However, there is one particular challenge that I am struggling with. ...

Discovering ways to access deeply nested JSON data in Vue JS

i am dealing with JSON data that includes payment information. I am facing issues retrieving the paid_amount and date for both cash_payment and installment_payment. { "response": [ { "status": "sold", "price": "1000 ...

The function within the Context Hook has not been invoked

My attempt to implement a signin method using the context hook is not working as expected inside the AuthContext file. When calling the signin method from the Home Page, neither the console.log nor the setUser functions are being executed inside the AuthC ...

Dropzone.js only allows one audio file and one image thumbnail file to be uploaded simultaneously

Is there a way to limit the types of files that can be uploaded through Dropzone.js? Specifically, I want to restrict users to uploading only one image and one audio file. ...

Struggling with integrating jQuery append into Backbone.js

Having trouble using jQuery.append() and backbonejs. Currently, when attempting to append, nothing happens (except the jQuery object is returned in the immediate window) and the count remains at 0. Manually adding the element has not been successful. I als ...

Order of Actions not being Dispatched by Redux Thunk

Using redux thunk presents a challenge for me. When I dispatch uploadClientImage, it creates an image object in the database and returns the image id. I require both image ids before creating client_info. The issue arises when the axios post to clients i ...

Issue encountered while running React on Mac: Error with ELIFECYCLE, spawn, ENOENT

After successfully creating a tester react file using create-react-app, I encountered errors when trying to run any other react file with "npm start." The errors I received were as follows: > react-scripts start sh: react-scripts: command not found npm ...

Ways to align two elements within the same level in the DOM?

Is it really impossible to have two elements render parallel to each other on the z-axis? Even with the same z-index, they are treated as being on different levels based on their order in the DOM. This can be a challenge when trying to display nearby eleme ...

I'm trying to display hidden forms on a webpage when a button is clicked using the DojoToolkit, but I'm having trouble figuring out what's going wrong with my code

Currently, I am trying to grasp the concepts of Dojotoolkit and my objective is to display a form when a button is clicked. Upon reviewing other examples, my code seems correct to me; however, there appears to be something crucial that I am overlooking but ...

Having trouble reaching an injected dependency beyond the controller method

Can an injected dependency on a controller be accessed outside of it? function clientCreateController(ClientsService, retrieveAddress) { var vm = this; vm.searchCep = searchCep; } function searchCep(cep) { retrieveAddress.find(cep) .success ...

Converting Node.js Date.toString() output into a time format in Go

My go service is currently receiving data from an external source. Here's how the data appears (in JSON format)- { "firstName": "XYZ", "lastName": "ABC", "createdAtTimestamp": "Mon Nov 21 2 ...

What is the best way to position a rectangle on top of a div that has been rendered using

I recently started using a waveform display/play library known as wavesurfer. Within the code snippet below, I have integrated two wavesurfer objects that are displayed and positioned inside div elements of type "container". My goal is to position my own ...

What is the process for retrieving the updated document from the findOneAndUpdate function?

Utilizing MongoDB with Node.js, I installed the MongoDB module using npm install mongodb. I encountered an issue where updating an existing document did not return the updated document; instead, it returned the original one. Even after setting the returnN ...

Steps to include a horizontal divider in the footer section of an angular-material table

Is it possible to add a line between the last row (Swimsuit) and the footer line (Total)? If so, how can I achieve this using Angular 15? https://i.stack.imgur.com/581Nf.png ...