Switching the color of NavLink text when onclick occurs

Is there a way to modify the text color of the links within the navbar using React?

navLink1{
color: black;
}

   
<div className="left-navlinks">
                    <img className="logo" src={logo}/>
                    <Link to="/"></Link>
                    <Link to="/home"> <div className="navlink1">Home</div></Link>
                    <Link to="/about"> <div className="navlink2">About</div></Link>
                    
</div>

I attempted to utilize the hover property for this purpose, however, it did not produce the desired result. I am looking to have the text color change to blue when a link is clicked and selected.

Answer №1

NavLink is a great solution for styling navigation items in React, as shown below:

navItem.module.css:

.left_navlinks a {
   color: black;
   text-decoration: none;
 }
 
 .left_navlinks a:hover,
 .left_navlinks a:active,
 .left_navlinks a.active {
   color: blue;
 }

App.js:

import React from "react";
import { NavLink } from "react-router-dom";
import classes from "./navItem.module.css";

class App extends React.Component {
   render() {
      return (
         <>
            <div className={classes.left_navlinks}>
               <img className="logo" src={logo} />
               <NavLink to="/"></NavLink>
               <NavLink to="/home" activeClassName={classes.active}>
                  Home
               </NavLink>
               <NavLink to="/about" activeClassName={classes.active}>
                  About
               </NavLink>
            </div>
         </>
      );
   }
}

export default App;

Answer №2

When using the Link component, it will display an <a> element on a webpage. If you want to alter its color, simply insert this style:

a {
  color: black;
}

To experiment with it, click here.

Answer №3

Instead of using a div, you can assign classes directly to links:

.navLink1{
color: black;
}

   
<div className="left-navlinks">
                    <img className="logo" src={logo}/>
                    <Link to="/"></Link>
                    <Link to="/home" className="navlink1"> Home</Link>
                    <Link to="/about" className="navlink2">About</Link>                    
</div>


Here is a sample implementation:

import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

import "./style.css";

function BasicExample() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/" className="navLink1">
              Home
            </Link>
          </li>
          <li>
            <Link to="/about" className="navlink2">About</Link>
          </li>
          <li>
            <Link to="/dashboard" className="navLink1">Dashboard</Link>
          </li>
        </ul>

        <hr />

        {/*
          A <Switch> looks through all its children <Route>
          elements and renders the first one whose path
          matches the current URL. Use a <Switch> any time
          you have multiple routes, but you want only one
          of them to render at a time
        */}
        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/dashboard">
            <Dashboard />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

// You can think of these components as "pages"
// in your app.

function Home() {
  return (
    <div>
      <h2>Home</h2>
    </div>
  );
}

function About() {
  return (
    <div>
      <h2>About</h2>
    </div>
  );
}

function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
    </div>
  );
}



export default function App() {
  return (
    <BasicExample/>
  );
}

Demo: https://stackblitz.com/edit/react-kcmdvt?file=src/App.js

Answer №4

I highly suggest utilizing styled-components to easily add CSS styles to your components.

To learn more about styling any component using styled-components, visit this link.

Answer №6

To ensure that the link remains active when clicked, you must pass a prop to the child component from the parent component and use a ternary operator to apply a className to the Link element that matches the active prop passed.

Here is an example:

import React from 'react';
import { Link } from 'react-router-dom';

function NavLink({ activeLink }) {
    return (
        <div className="left-navlinks">
            <img className="logo" src={logo}/>
            <Link to="/"></Link>
            <Link to="/home"> <div className={activeLink === home ? `active-navlink` : `normal-navlink`}>Home</div></Link>
            <Link to="/about"> <div className={activeLink === about ? `active-navlink` : `normal-navlink`}>About</div></Link>                    
        </div>
    )
}

export default NavLink

Answer №7

Instead of having a separate div element, you can simply add the className directly to the Link component without the need for individual classNames.

If you want to change the color of the link when it is selected, you can use the 'active' selector or if you prefer it to change only after being clicked, you can use 'visited'.

Here is an example using the 'active' selector:

navLink: {
  color: black;
}
navLink:active {
  color: blue;
}

I'm assuming you are importing a css file for the styling?

<div className="left-navlinks">
                    <img className="logo" src={logo}/>
                    <Link to="/"></Link>
                    <Link to="/home" className="navLink">Home</Link>
                    <Link to="/about" className="navLink">About</Link>
                    
</div>

Answer №8

To change the color of a link by clicking the text, you need to utilize an onClick method and state to store the new color preference. The code snippet provided below demonstrates how to achieve this functionality within a functional component:

    const [linkColor, setLinkColor] = useState("");

  const handleColorChange = () => {
     setLinkColor("blue");
  }

  return (
    <div className="left-navlinks">
      <div className="navlink1" style={{ color: linkColor }} onClick={handleColorChange}>Home</div>
    </div>
  );

Answer №9

In my opinion, using NavLink from react-router-dom is more preferable to Link. NavLink returns an anchor tag, allowing you to target them specifically with CSS styling. For example, you could use .navlinks > a { color: black } to change the color of the links. If you want to change the color when the link is active, you may need to use !important to override any existing styles. I hope this solution proves helpful.

Answer №10

const currentLocation = useLocation();
<div>
    <img className="logo" src={logo}/>
    <Link to="/"></Link>
    <Link to="/home" className={currentLocation.pathname === "/home" ? "navLink1": ""}> Home</Link>
    <Link to="/about" className={currentLocation.pathname === "/about" ? "navLink1":""}> About</Link>
</div>

Please give this a try, it has been effective for me.

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

Bootstrap loader failed to load, causing issues with CSS in Django

Just getting started with Django and Python, I created a test project that was working fine until I attempted to change the design by adding some CSS, JS, and image files. I also installed Bootstrap, but when I uploaded the files, my page couldn't fin ...

Tips for categorizing the properties of an object based on their types

interface initialStateInterface { user: object; age: number; } const initialState = { user: { username: "", email: "" }, age: 0, }; In this code snippet, I have defined an interface type for the initial state containing a user ...

Sending information through clicks from one component to another in a React application

I'm a beginner in React and facing an issue with passing data (director, nonDirector) from my child functional component to a parent class component. Below is the code I've been working on, what changes should I make to get it to function correct ...

Even though I've already assigned a key prop in React, I am still receiving a warning message about the

In the following code snippet, I am creating a note card element with a specific key. However, whenever I attempt to edit my note element, I encounter a warning that states: Warning: Each child in a list should have a unique "key" prop. Here is a portion ...

The process of parsing HashMap failed due to an unexpected encounter with an Array, when an Object

Currently, I am in the experimental phase of creating an action at Hasura using a Node.js code snippet hosted on glitch.com. The code snippet is as follows: const execute = async (gql_query, variables) => { const fetchResponse = await fetch( "http ...

Highcharts feature enhancement: Adjusting zIndex of legendItem on mouseover/mouseout

I have a chart that includes a 'total' sum value series alongside other values. My goal is to initially hide or place this 'total' column behind the others, and then bring it to the front when the series' legendItem is hovered ove ...

ajax fails to send the variables, instead sending undefined values

In my HTML code, I have inputs and checkboxes. The JavaScript code collects the data from the inputs, and through AJAX, it should send the information to PHP where it is received and stored in the session. However, when sending the array to the PHP file v ...

A Guide to Sorting Nested Lists with SortableJS and jQuery

I have been experimenting with SortableJS and jQuery SortableJS Binding in order to create a nested list, capture the new order of the list and its children (resembling a hierarchical structure) using console.log(). I attempted the solution provided in th ...

The typescript MenuProvider for react-native-popup-menu offers a range of IntrinsicAttributes

Looking to implement drop-down options within a Flatlist component, I've utilized the React Native Popup Menu and declared MenuProvider as the entry point in App.tsx. Encountering the following error: Error: Type '{ children: Element[]; }' ...

Disable the borders on HTML input fields

I am looking to implement a search feature on my website. It seems that in Firefox and Internet Explorer, the search function appears fine without any unexpected borders. Firefox IE However, when viewing the search function in Chrome and Safari, there ...

Using plain JavaScript (without JQuery) to specify the AJAX content type

I have been working on form submission using AJAX with plain JavaScript, without any external libraries. However, I encountered an issue where the PHP doesn't seem to parse the data correctly when I try to parse the form. After doing some research o ...

Is there a way to store the outcome of an HTTP GET call in Angular 7 as a JSON file?

Hey there! I'm currently working on a web app that needs to make regular calls to a remote API. Since the response will always be consistent, I am planning to optimize the site's performance by storing the response data in a local JSON file. This ...

What are some ways to improve the performance of a React-virtualized list running at less than 60 frames

I've been working on developing a post feed similar to the one found on Instagram's main page. To achieve this, I have implemented Infinite-loader for fetching, Window-scroller for using the window as the scroll, auto-sizer for sizing the list ac ...

The children constants are not inheriting the boolean value

I am facing an issue while trying to access the value of removefromcart through showRemoveFromCart. It seems that it's not working and the remove from cart button is not rendering properly. Oddly enough, I can access the value of addtoCart without any ...

Issue with Navbar Header: Troubleshooting and Solutions

I'm having trouble with my navigation bar. I want to add "3" under the dropdown section and set up multiple menu items, such as Link 4. I couldn't figure out how to do this in my code... Could it be that Bootstrap doesn't support this feat ...

Retrieve a list of IDs specifically for the array objects that have been modified in Mongodb

In this instance, I am showcasing a snippet from my "messages" collection. {[ _id: xxx, shipment: { _id: xxx }, messages: [ { _id: 123, origin: 'driver' isRead: false, ... }, { _id: 234, ...

Is it possible to submit two forms simultaneously using jQuery or AJAX?

My plan is to save 2 forms, with the first form providing the Foreign key for the second form. This is my attempt at saving this using JavaScript: $("#btnSave").click(function (e) { e.preventDefault(); $('#workForm').submit(); ...

Querying mongoose with $near or other fields

I'm trying to retrieve documents using a query $or on different fields along with a $near query that is causing issues. Schema locationSchema{ ... beacon: String, access_point: String, gps: [], ... } locationSchema.index({ gps: ...

Having difficulty creating a file labeled as "undefined" within the grunt plugin

As a newcomer to writing grunt plugins, I've encountered an issue when attempting to run it: Running "inject_css:dev" (inject_css) task Warning: Unable to write "undefined" file (Error code: undefined). Use --force to continue. The structure of my p ...

How does my navigation and slider function in Internet Explorer 10?

Currently, I am in the process of developing my own website at www.heike-waltz.de In the past, I relied on conditional comments for IE, but now that this is no longer an option for IE10, I am facing some issues that I'm not sure how to resolve. Whil ...