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

Identify the currently active subitem within the item-active class in a PHP carousel slider

I am working on creating an image carousel slider with 4 items and 4 slides each. These images will act as radio buttons, and I want to highlight the slide corresponding to the selected radio button. So, when the carousel loads, the selected slide should b ...

Using JQuery selectors in conditional statements

In the context of my webpage, clicking on a tag filters and displays corresponding posts. I now need to handle pagination to navigate to the next set of posts. However, I am facing difficulties with the JavaScript if statement in jQuery, where I struggle ...

Exploring data visualization and time zones with highcharts on a React platform

I am working on a chart component in React that is populated with data from an API. The array of objects I receive contains rows structured like this: Rows: [ { EffectiveTime: "06-Nov-2020 00:00:00", FieldName: "GEN_EXP", Re ...

When utilizing create-react-app with an express backend, everything runs smoothly on a local machine. However, issues arise with

I recently followed a tutorial on creating an app using create-react-app with an express backend and the Spotify API. I've been struggling to deploy it to Heroku ever since. Here's the link to the tutorial: https://medium.com/@jonnykalambay/now-p ...

Modify the conditions of a CSS file in Bootstrap using JavaScript

My project requires internationalization support for right-to-left languages like Arabic and Hebrew, so I need to modify some Bootstrap classes (such as col) to float right instead of left. I am using create-react-app with babel/webpack and react-bootstra ...

Issue with MUI Button: Color not displaying

My attempt to customize button colors using the MUI package is not working as expected. Despite setting the colors in the theme injection, they only appear on hover. Here's a snippet of my code: const theme = createTheme ({ // within themes, must pa ...

AngularJS: Display the last four characters of a string and substitute the rest with 'X'

I am attempting to change the characters with X and make it look something like this XXXXXT123 This is what I have tried: var sno = 'TEST123'; alert(sno.slice(0,3).replaceWith('X')); However, I encountered an error in the console ...

Guide to deploying a Node.js application with a Gruntfile on Heroku

I have encountered an issue while trying to deploy my Node.js application to Heroku using the BUILDPACK_URL. Despite searching for a solution, I have been unable to find a suitable answer. Here is the procedure that I followed: heroku create myapp hero ...

How to iterate through an array of objects in Javascript and extract an array of strings

I am dealing with an array of objects that looks like this: [{"key":"aaa","value":true},{"key":"bbb","value":false},{"key":"ccc","value":true}] My goal is to iterate through it and extract an array containing only the keys: ["aaa", "bbb", "ccc"] I am u ...

Issue with rendering icon in react material-table after clicking

After spending several days searching, I am still unable to figure it out. What I want is for the visibility icon to change to "hide" when clicked. However, I'm facing an issue where it's not rendering automatically. I have to type something in t ...

Adjust the width to ensure the height is within the bounds of the window screen?

I am currently in the process of developing a responsive website, and my goal is to have the homepage display without any need for scrolling. The layout consists of a 239px tall header, a footer that is 94px tall, and an Owl Carousel that slides through im ...

Is it possible to customize the close icons on the autocomplete feature in Material UI?

Is there a solution to change the icon while keeping its function when clicked? I am looking to replace this Icon <Autocomplete multiple id="checkboxes-tags-demo" options={top100Films} disableCloseOnSelect getOpt ...

No information available at the moment

When the data is not present, it displays as "display none"... However, I want it to show "no data found" This is the current code if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].styl ...

Customize the Material-UI's private styling

Is it possible to override a private style in material-ui? I have a specific requirement to change the font color of the slider valueLabel. Basically, I want to achieve this: Instead of this: I attempted to globally override the style without success ...

Is it feasible to incorporate an external library as a script within a class or functional component in React?

Welcome and thank you for taking the time to read this question! I am currently working on a project where I need to load a TIFF image. After researching, I found a library that can help with this task: https://github.com/seikichi/tiff.js There is also ...

Retrieving Mouse Coordinates using Ajax in PHP

I'm wondering if it's feasible to send an Ajax request with mouse coordinates using PHP. For instance, I am fetching a page with cUrl and would like to trigger a mouse movement event on that page. At this point, I haven't written any code ...

Is it possible to redirect a URL with a readyState of 4?

Is it possible to redirect to a page when the readyState is equal to 4? //load the send form if (sendRequest) { sendRequest.open("POST", urlRequest, true); sendRequest.setRequestHeader("Content-Type", "application/x-www-form-urlenc ...

Steps to design a unique input radio button with embedded attributes

In my current project, I am utilizing react styled components for styling. One issue that I have encountered is with the text placement within a box and the need to style it differently when checked. What have I attempted so far? I created an outer div a ...

Having difficulty creating a shadow beneath a canvas displaying Vega charts

I'm looking to create a floating effect for my chart by adding shadows to the canvas element that holds it. Despite trying various methods, I can't seem to get the shadow effect to work. Here is the code snippet I have for adding shadows: <sc ...

Convert a comma-delimited string containing a numerical value into a floating point number, for example, 3.00

I need to extract a number from a value that is returned with commas around it. My goal is to convert this value into a number so that I can compare it against another number in my code later on. However, I'm facing difficulties in reliably extracting ...