Adjust the color of an individual anchor link when hovering using React.js

Currently, I am attempting to modify the color of a specific anchor link when it is hovered in React.

To achieve this, I have created two functions named handleMouseEnter and handleMouseLeave:


handleMouseEnter() {
    this.setState({ isMouseInside: true });
}

handleMouseLeave() {
    this.setState({ isMouseInside: false });
}

I then defined the linkstyle as follows:


let linkStyle;
if (this.state.isMouseInside) {
    linkStyle = { color: '#6996FF', cursor: 'pointer', textDecoration: "none" };
} else {
    linkStyle = { color:"#999D9F", textDecoration: "none" };
}

Subsequently, I integrated it into my HTML code:

<ul style={{listStyle:"none"}} color={this.state.isMouseInside ? '#999D9F' : 'white'}
    className="footer-links">
    <li>
        <a style={linkStyle} onMouseEnter={this.handleMouseEnter}
           onMouseLeave={this.handleMouseLeave} href="#/category/1">
            Pants
        </a>
    </li>
    <li>
        <a style={linkStyle} onMouseEnter={this.handleMouseEnter}
           onMouseLeave={this.handleMouseLeave} href="#/category/2">
            Shirts
        </a>
    </li>
    <li>
        <a style={linkStyle} onMouseEnter={this.handleMouseEnter}
           onMouseLeave={this.handleMouseLeave} href="#/category/3">
            Dress
        </a>
    </li>
    <li>
        <a style={linkStyle} onMouseEnter={this.handleMouseEnter}
           onMouseLeave={this.handleMouseLeave} href="#/category/4">
            Shoes
        </a>
    </li>
    <li>
        <a style={linkStyle} onMouseEnter={this.handleMouseEnter}
           onMouseLeave={this.handleMouseLeave} href="#/category/5">
            Jackets
        </a>
    </li>
</ul>

All anchor links change color on hover because there is only one state variable isMouseInside.

My question now is whether there is a more efficient way to accomplish this without having to define multiple variables and set the state for each anchor link individually?

Answer №1

When it comes to styling links with a hover effect, Links have a built-in event that can be easily utilized. Simply assign an id or class to the specific link and add your CSS styles:

// HTML
<a href="" id="linkid">Link</a>

// CSS
#linkid {
  color: #999D9F;
  text-decoration: none;
}

#linkid:hover {
  color: #6996FF;
  cursor: pointer;
  text-decoration: none
}

For those using styled-components, you can create a styled component like this:

const SpecialLink = styled.a`
  color: #999D9F;
  text-decoration: none;

  &:hover {
    color: #6996FF;
    cursor: pointer;
    text-decoration: none
  }
`;

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

Is my utilization of Flexbox and media queries incorrect?

Currently, I am practicing flexbox and breakpoints in material UI using React.js and I am attempting to achieve a layout similar to this: https://i.sstatic.net/vAkdo.png My goal is to have the product images and type displayed in columns, while the produc ...

What could be causing a functional component's child component to be using stale props?

I am currently working with Next JS, but the process is similar. I have refined the code and eliminated irrelevant parts. My goal is to create a form where new fields (child components) can be added dynamically. The default setting will be 1 field, with a ...

Try implementing transform translate with absolute coordinates when positioning elements on a webpage

If I wanted to create a box that moves along with the mouse cursor, I could achieve that using the code below. document.addEventListener('mousemove', (e) => { document.documentElement.style.setProperty('--mouse-x', e.clientX ...

Encountering issues while attempting to deploy React App on Git Hub Pages

After attempting to follow a ReactJS tutorial, I encountered an error when trying to deploy the code on Github pages. Despite searching for solutions, nothing seems to be working. Given my limited experience with Git and GitHub, I would greatly appreciat ...

What is the best way to adjust the width of a column to perfectly fit its contents when using IE9 compatibility mode?

Within my HTML code, I've included the table displayed below. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <style type="text/css"> table, td, tr, th{ border:1px; } .onepx{ ...

What is the best way to vertically center my text on the right and left sides of an image?

I am struggling to align the text on the left and right side of my image to the vertical center. It seems like my containers are not recognizing their height. How can I resolve this issue? Here are the CSS and HTML snippets for your reference: .footer { ...

WebpackError: The assignment of the property 'emulateTransitionEnd' to an undefined value cannot be completed

I've been attempting to implement Bootstrap in GatsbyJs, but it just seems to continually let me down. Is there a legitimate method to import Bootstrap without encountering the following error? WebpackError: Cannot set property 'emulateTransitio ...

Please provide TypeScript code for a React wrapper function that augments a component's props with two additional functions

During the course of my project, I implemented a function wrapping React component to incorporate undo/redo functionality using keyboard shortcuts Ctrl+Z and Shift+Ctrl+Z. Here is an example: import React from 'react'; interface WithUndoRedoProp ...

What is the best way to link various stylesheets to a Rails project?

In my project, I have a main stylesheet called application.css included in the layout file layouts/application.html.erb: <%= stylesheet_link_tag "application" %> However, there is a specific section of the website where I want to use a different st ...

Send the form using an alternative method to avoid using preventDefault

Having some trouble with my website's sign-in functionality not working properly on all browsers. In Firefox, I keep getting a "ReferenceError: event is not defined" error. I've read through various posts about preventDefault behaving differentl ...

The Realm of React Native

-Apologies for my limited English skills. -I am new to REACT NATIVE. Whenever I run "npm start" in the command prompt as an administrator, I encounter the following errors. -I have spent hours trying to fix it with no luck. Thank you all for your assistanc ...

The handleSumbit feature seems to be malfunctioning in a React Native application that utilizes React-Hook-Form in combination with yup

Greetings, I am currently utilizing React-hook-form and yup for validation in my React Native project. However, I have run into an issue with the handleSubmit function not functioning properly in my ResetPasswordScreen component. Strangely enough, a simila ...

Returning AJAX HTML Page Code (Duplicate)

I've been attempting to create a basic Search Bar, but when I try to send the data to PHP and use ALERT for testing purposes, it alerts back the entire HTML page content. Despite searching extensively, I couldn't find a solution. Here's my ...

Centralize Checkboxes with Bootstrap

Is there a way to center the checkbox input both vertically and horizontally within its parent column? The image below illustrates the parent column and checkbox. I have attempted using classes like text-centered, d-flex justify-content-center, and align- ...

Utilize Google Maps API to showcase draggable marker Latitude and Longitude in distinct TextFields

I am currently utilizing the Google Maps example for Draggable markers. My objective is to showcase the latitude and longitude values within separate TextFields, where the values dynamically change as I drag the marker. Once the user stops dragging the mar ...

Having trouble sending `req.params` through http-proxy-middleware in a NodeJS/Express application?

I'm still getting the hang of Node, and I've run into an issue with passing request parameters using http-proxy-middleware. Every time I try, I keep getting a 404 error. This is my express listener setup: app.put("/api/markets/:id",()=>{..c ...

Explain the assigned identifier for the input parameter

Trying to send data (Collection<Cars>) using AJAX with JQuery, but struggling to define the object in my Action input parameter. I attempted to define it as FormCollection and received all data successfully. However, my goal is to define it as IColle ...

Diving into the world of styling: Comparing MUI v5 with @mui/material/styles

After seeking clarification on theming MUI v5 in this question, I still find myself struggling to grasp the differences between using @emotion/react API and @mui/material/styles. While the migration guide offered some insight into specific implementation ...

Steps for achieving uniform positioning of a div element that dynamically appears within a table with two rows and four table data cells

If I want to display the same div in different positions dynamically on my page, how can I achieve that? My page has a table with two rows and two columns, each containing an Embed button. When these buttons are clicked, a div is shown with a list of site ...

The dropdown menu in the right-aligned navbar section on Bootstrap displays a panel arrow to the left

I'm currently utilizing bootstrap to design a top navigation bar for an ecommerce website that resembles Facebook's layout. I have included a dropdown option on the right side of the top link labeled "Account" to display various account related a ...