Leverage the power of Reactjs to add hover effects to a mapped

I am facing a challenge in styling the ListItem on hover. The issue arises when the list is dynamically generated, causing all list items to change style simultaneously when hovered over. How can I target only one element for styling? Below is the code snippet where I am attempting to style the prop.icon and ListItemText upon hover.

Sidebar.js

var links = (
    <List className={classes.list}>
      {routes.map((prop, key) => {
    

        if (prop.path === "/login") {
          return;
          
        }

        return (
          <NavLink
            to={prop.layout + prop.path}
            className={classes.item}
            activeClassName="active"
            key={key}
          >
            
            <ListItem button className={classes.itemLink} onMouseEnter={MouseEnter} onMouseLeave={MouseLeave}>
            <prop.icon
                className={classNames(classes.itemIcon)}
              />
             
              <ListItemText
                primary={prop.name}
                className={classNames(classes.itemText)}
                disableTypography={true}
              />
            </ListItem>
          </NavLink>
        );
      })}
    </List>
  );

MouseEnter & MouseLeave

  const MouseEnter = (e) => {
    
    setHovered(true);
  }
  const MouseLeave = (e) => {
    setHovered(false);
  }

Answer №1

Implementing this design with CSS is quite straightforward:

.list-item:hover{
  background-color: teal;
  color: black;
}



/* This section is purely for styling purposes, you can ignore it */

ul{
  list-style-type: none;
}

li{
  padding: 1rem;
  cursor: pointer;
  border: solid 1px gray;
  margin: 0.5rem;
}
<script src="https://kit.fontawesome.com/a076d05399.js"></script>


<ul >
  <li class="list-item" >
      <span  >&#9824; </span>spades
  </li>
  <li class="list-item">
      <span  >&#9827; </span>clubs
  </li>
  <li class="list-item">
      <span  >&#9830; </span>dιmonds
  </li>
</ul>
        

Alternatively, you can achieve the same result with your provided code:

//links.css
.list-item:hover{
  background-color:blue;
}

//links.js
import "./links.css"

var links = (
    <List className={classes.list}>
      {routes.map((prop, key) => {


        if (prop.path === "/login") {
          return;

        }

        return (
            <NavLink
                to={prop.layout + prop.path}
                className={classes.item}
                activeClassName="active"
                key={key}
            >

              <ListItem button className={classes.itemLink + " list-item"} onMouseEnter={MouseEnter} onMouseLeave={MouseLeave}>
                <prop.icon
                    className={classNames(classes.itemIcon)}
                />

                <ListItemText
                    primary={prop.name}
                    className={classNames(classes.itemText)}
                    disableTypography={true}
                />
              </ListItem>
            </NavLink>
        );
      })}
    </List>
);

Answer №2

I found success by utilizing the active index in the array rather than relying on boolean values. sidebar.js

 const [hovered, setHovered] = useState(-1);

  const MouseEnter = (index) => {
    setHovered(index);
  }
  const MouseLeave = () => {
    setHovered(-1);
  }
  
  
  var links = (
    <List className={classes.list}>
      {routes.map((prop, index, key ) => {
    

        if (prop.path === "/login") {
          return;
          
        }

        return (
          <NavLink
            to={prop.layout + prop.path}
            className={classes.item}
            activeClassName="active"
            key={key}
          >
            
            <ListItem button className={hovered === index ? 'hoverLinear' : classes.itemContainer} onMouseEnter={() => MouseEnter(index)} onMouseLeave={MouseLeave}>
              <prop.icon
              
                className={classNames(classes.itemIcon)}
                 style={hovered === index ? {color: 'white'} : {color: "#8B2CF5"}
              />
              <ListItemText
                primary={prop.name}
                className={classNames(classes.itemText, ' mx-10')}
                style={hovered === index ? {color: 'white'} : {color: "#3A448E"}}
                disableTypography={true}
              />
            </ListItem>
          </NavLink>
        );
      })}
    </List>
  );

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

Are there any jQuery Context Menu plugins clever enough to handle window borders seamlessly?

After reviewing UIkit, as well as some other jQuery Context Menu plugins, I have noticed that they all tend to exhibit a similar behavior: The actual menu div renders outside the window, causing valuable content to be hidden from view. Is there a way to ...

A guide on using jQuery-Tabledit and Laravel to efficiently update table rows

In Laravel, it is necessary to include the row ID in the request URL to update it, for example: http://localhost/contacts/16 The challenge arises when using jQuery-Tabledit, which requires a fixed URL during initialization on page load. Hence, the query ...

Generating random numbers using click events in a React application.Let's explore how to create

My goal is to generate random numbers between 1 and 50 when a button is clicked. Below is the component I have created for this functionality: import React from 'react' import './Board.css'; const Board = () => { let rand; f ...

Having difficulty assigning a selected value in select2 using JavaScript with Ajax mode

I am trying to use a select2 element that loads data from a database using ajax. My goal is to load the value from the database and have it selected as the default value in edit mode. However, I am encountering issues with using the trigger function to ach ...

compress a website to display advertisement

Here is a JSFiddle link I would like to share with you: I am currently working on squeezing the webpage to display an ad on the right side. http://jsfiddle.net/5o6ghf9d/1/ It works well on desktop browsers, but I am facing issues with iPad Safari/Chrome ...

Issue with prop inheritance in componentInheritance problem with passing props to

How can I pass the state function setMyChoice as a prop to the GamePlay component in a rock paper scissors Nextjs application? The goal is to produce a value for comparison. In the Gameplay component, I then pass a prop to another component called PlayButt ...

Node.js: Steps for receiving an ArrayBuffer in a $http request

I made a request using $http.post from Angular.js to Node.js, expecting to receive an ArrayBuffer. Here is the code snippet: $http.post('/api/scholarships/load/uploaded-files', Global.user, {responseType:'arraybuffer'}).success(functi ...

What is the best method to display an asterisk (*) in red while using React and Material UI

In my form, I want to indicate required fields with a red star (*). Is there a way to display the star in red color? Also, why does the border turn blue when I click on an input field? Here is the code and screenshot for reference: https://codesandbox.io/ ...

Tips for Successfully Passing Objects Between Node.js and MySQL

I'm currently struggling with passing an object from Node.js to a MySQL database. The issue arises when attempting to use the INSERT method, as it only allows for strings to be passed. Any attempts to pass an object result in an error. My current cod ...

Challenges with CORS in React and Entity Framework Core API Integration

I've been attempting to make a simple http request using the fetch method for the past couple of days, but I'm still encountering a CORS error. I tried adding the HTTP header to the .htaccess file, but it doesn't seem to be effective. fetch ...

What is the method for incorporating a link in an accordion header next to the toggle button with Bootstrap?

I'm attempting to enhance a link in the accordion-button so that only the arrow is clickable for collapsing. The CSS I added below makes the arrow clickable, but I am having trouble getting the link in the accordian-button to work. I want users to be ...

Navigate using history.push with user Logout Icon

Currently, I am utilizing a Material UI icon as a logout button in my project. Here is how I have implemented it: function logout(props:any){ localStorage.removeItem("token"); return( <Redirect to="/login" /> ) //props.history.push("/log ...

Can a function be activated in JavaScript when location permission is declined?

Background: Following up on a previous question regarding the use of getCurrentPosition and async functions. I am currently working on The Odin Project and attempting to create a basic weather application. My goal is to include a feature that automatically ...

Efficiently adjusting the height of a sticky sidebar

I am currently implementing a Bootstrap grid with two divs in a row. I need my reply-container to be fixed (sticky). However, when setting position: fixed; it is affecting the element's width by adding some additional width. With position: sticky, set ...

Designing an interactive HTML table that adapts to various screen

Currently utilizing Bootstrap to create a responsive HTML table on smaller devices like the iPad, but seeking a more polished and professional alternative. Searching for a JQuery/JavaScript or CSS solution without relying on plugins. Would appreciate any ...

Attempting to send a POST request, only to be informed by the form that it is devoid of

I have been struggling with this problem for some time now. I implemented the category_create_post functionality in the categoryController, and everything seems to be set up correctly. I also configured the category_form.ejs to accept user input. However, ...

Is there a way to improve scrolling speed on Mobile Safari?

I'm currently working on a project utilizing angularjs and bootstrap, aiming to replicate iOS's navigationController feature. However, I'm encountering speed issues, particularly when scrolling between views on mobile safari iOS. The transi ...

Problem with Angular2, NodeJS, and Passport Integration

At the moment, my Angular2 front-end is running on localhost:3000 while the NodeJS back-end (using KrakenJS) is running on localhost:8000. When I input the credentials and make a call to the this.http.post('http://localhost:8000/login', body, { h ...

What should be the output when ending the process using process.exit(1)?

I need to update my code by replacing throw new Error('Unknown command.') with a log statement and process.exit(1);. Here is the example code snippet: private getCommandByName = (name: string): ICommand => { try { // try to fetch ...

Step-by-step guide on how to configure the URL path in an AJAX function call

How can I dynamically set the URL path in an AJAX function call when clicking on a page so that the page name is included in the URL? For example, if I click on a particular page (let's say the "ask" page on Stack Overflow), the URL should look like: ...