You could keep an object in your state instead of a boolean, that has a key indicating if the object with that particular key as index is hovered or not.

Example

class App extends React.Component {
  state = {
    arr: [{ text: "foo" }, { text: "bar" }],
    isHovered: {}
  };

  handleMouseEnter = index => {
    this.setState(prevState => {
      return { isHovered: { ...prevState.isHovered, [index]: true } };
    });
  };

  handleMouseLeave = index => {
    this.setState(prevState => {
      return { isHovered: { ...prevState.isHovered, [index]: false } };
    });
  };

  render() {
    const { arr, isHovered } = this.state;

    return (
      <div>
        {arr.map((el, index) => (
          <Child
            onMouseEnter={() => this.handleMouseEnter(index)}
            onMouseLeave={() => this.handleMouseLeave(index)}
            text={el.text}
            isHovering={isHovered[index]}
            key={index}
          />
        ))}
      </div>
    );
  }
}

function Child({ onMouseEnter, onMouseLeave, text, isHovering }) {
  return (
    <div onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>
      {text} {isHovering && " (hovering!)"}
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

Answer from Tholle on Stack Overflow
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
How to add a hover effect on a React Icon - JavaScript
July 20, 2021 - following the Doc on React icon on the link below its gives instruction on how to style the icons from React Icon , would anybody tell me how to add a hover effect to the icon since its not mentioned in the documentation. import { IconContext } from "react-icons"; Github Doc
Discussions

Simple React hover icon example - GSAP - GSAP
Hi. I need some basic help with gsap.timeline() in a react environment. See my code below: import React, { useRef, useEffect } from 'react' import gsap, { TweenMax, Linear } from 'gsap'; import { ReactComponent as Twitter } from '../assets/svg/social/twitter.svg' const NavBar = () => { let twi... More on gsap.com
🌐 gsap.com
March 24, 2020
How can I show the button only when the mouse hovers on the color?
I know this isn’t the point of your post, but hiding and showing critical user controls as the mouse hovers over things leads to poor user experiences because the user has no indication of what they need to do to “Add” a color, or that doing so is even possible. Instead, have the control default to some muted state, then become more vibrant on hover. Some possibilities: change the color of the buttons always show a + icon, then reveal the word “Add” on hover hide/show the border of the button slightly change the opacity As a bonus, if there is an undiscovered bug in your code, the user can still use the control even if it’s muted. If you completely hide controls and you have a bug, the user may be stuck. More on reddit.com
🌐 r/reactjs
6
1
March 6, 2022
css - Show a component on hover in reactjs - Stack Overflow
I've created several sections with the heading of the specific content. I want to show a short sneak preview on hovering above the different section. Does anyone knows how to create a More on stackoverflow.com
🌐 stackoverflow.com
Display text when hovering over an icon using React-Icon Library
Show activity on this post. so I am attempting to display text when you hover over a mouse. I am using React-Icons library and for styling using Styled-Components More on stackoverflow.com
🌐 stackoverflow.com
🌐
GreenSock
gsap.com › forums
Simple React hover icon example - GSAP - GSAP
March 24, 2020 - Hi. I need some basic help with gsap.timeline() in a react environment. See my code below: import React, { useRef, useEffect } from 'react' import gsap, { TweenMax, Linear } from 'gsap'; import { ReactComponent as Twitter } from '../assets/svg/social/twitter.svg' const NavBar = () => { let twi...
🌐
Reddit
reddit.com › r/reactjs › how can i show the button only when the mouse hovers on the color?
r/reactjs on Reddit: How can I show the button only when the mouse hovers on the color?
March 6, 2022 -

I wanted to show the button once you hover on the specific color. However, what happens is, hovering on one color will also show the button for other colors of the same products. Also, the button is on the left side part, so if I'll hover to go to the left side, the button won't appear anymore.

How can I fix this? Any help would be appreciated. Thank you

This is also in codesandbox as well: https://codesandbox.io/s/efqrhd?file=/src/App.js

<Stack
        direction={{ xs: "column", sm: "row" }}
        spacing={{ xs: 1, sm: 2, md: 4 }}
      >
        <Grid item xs>
          {searchList.map((item, index) => (
            <List key={item.id + item.color}>
                {Object.entries(item.colorMap).map((color, i) => (
                  <div key={i}>
                    {color[1] !== 0 ? (
                      <>
                        <Stack direction="row" spacing={2}>
                          <Grid
                            item
                            xs
                            key={i}
                            onMouseEnter={(e) => showButton(e)}
                            onMouseLeave={(e) => hideButton(e)}
                          >
                            {color[0]}
                          </Grid>

                          {display === true && (
                            <>
                              <Grid item xs className={display}>
                                <Button
                                  onClick={(e) =>
                                    handleAdd(
                                      item.id,
                                      item.prodName,
                                      item.price,
                                      item.size,
                                      item.cat,
                                      color[0]
                                    )
                                  }
                                >
                                  Add
                                </Button>
                              </Grid>
                            </>
                          )}
                        </Stack>

                      
                    ) : (
                      <>2</>
                    )}
                    <br />
                  </div>
                ))}
              </Paper>
            </List>
          ))}
        </Grid>
      </Stack>
Top answer
1 of 1
90

You can use onMouseOver and onMouseOut to change the state and render a component conditionally based on the value of the state.

See it in action:

  • Hooks Implentation: https://codesandbox.io/s/react-hover-example-hooks-0to7u
  • Class Implemntation: https://codesandbox.io/s/XopkqJ5oV

Hooks:

import React, { useState } from "react";
import { render } from "react-dom";

const HoverableDiv = ({ handleMouseOver, handleMouseOut }) => {
  return (
    <div onMouseOver={handleMouseOver} onMouseOut={handleMouseOut}>
      Hover Me
    </div>
  );
};

const HoverText = () => {
  return (
    <div>
      Hovering right meow!
      <span role="img" aria-label="cat">
        
      </span>
    </div>
  );
};

const HoverExample = () => {
  const [isHovering, setIsHovering] = useState(false);
  const handleMouseOver = () => {
    setIsHovering(true);
  };

  const handleMouseOut = () => {
    setIsHovering(false);
  };

  return (
    <div>
      {/* Hover over this div to hide/show <HoverText /> */}
      <HoverableDiv
        handleMouseOver={handleMouseOver}
        handleMouseOut={handleMouseOut}
      />
      {isHovering && <HoverText />}
    </div>
  );
};

Class:

import React, { Component } from "react";
import { render } from "react-dom";

const HoverableDiv = React.memo(({ handleMouseOver, handleMouseOut }) => {
  return (
    <div onMouseOver={handleMouseOver} onMouseOut={handleMouseOut}>
      Hover Me
    </div>
  );
});

const HoverText = () => {
  return (
    <div>
      Hovering right meow!
      <span role="img" aria-label="cat">
        
      </span>
    </div>
  );
};

class HoverExample extends Component {
  constructor(props) {
    super(props);
    this.handleMouseOver = this.handleMouseOver.bind(this);
    this.handleMouseOut = this.handleMouseOut.bind(this);
    this.state = {
      isHovering: false
    };
  }

  handleMouseOver() {
    this.setState(() => ({
      isHovering: true
    }));
  }

  handleMouseOut() {
    this.setState(() => ({
      isHovering: false
    }));
  }

  render() {
    return (
      <div>
        {/* <HoverText /> gets shown when mouse is over <HoverableDiv /> */}
        <HoverableDiv
          handleMouseOver={this.handleMouseOver}
          handleMouseOut={this.handleMouseOut}
        />
        {this.state.isHovering && <HoverText />}
      </div>
    );
  }
}
🌐
Medium
medium.com › @glasshost › show-an-element-or-text-on-hover-in-react-44a15aa61f47
Show an Element or Text on Hover in React | by Glasshost | Medium
May 1, 2023 - import React, { useState } from 'react'; const HoverComponent = () => { const [isHovering, setIsHovering] = useState(false); return ( <div onMouseEnter={() => setIsHovering(true)} onMouseLeave={() => setIsHovering(false)} > {/* Add your content here */} {isHovering && ( <div style={{ backgroundColor: 'blue', color: 'white', padding: '10px' }}> {/* Add the element or text that you want to show on hover */} </div> )} </div> ); }; export default HoverComponent;
Find elsewhere
🌐
CodeSandbox
codesandbox.io › s › show-icon-on-hover-z25pri
Show icon on hover - CodeSandbox
May 20, 2023 - Show icon on hover by rafaeldcf using @emotion/react, @emotion/styled, @mui/icons-material, @mui/material, loader-utils, react, react-dom, react-scripts
Published   May 20, 2023
Author   rafaeldcf
🌐
Scrimba
scrimba.com › learn › react › display-icons-on-hover-cv8JEyU6
Display Icons on Hover
Learn to code with interactive scrims. Our courses and tutorials will teach you React, Vue, Angular, JavaScript, HTML, CSS, and more. Scrimba is the fun and easy way to learn web development.
Published   November 12, 2019
🌐
GitHub
github.com › react-icons › react-icons › issues › 403
How to :hover · Issue #403 · react-icons/react-icons
January 17, 2021 - How to set :hover value on react-icons ? No one assigned · No labels · No labels · No type · No projects · No milestone · None yet · No branches or pull requests ·
Author   andreferreiradaweb
🌐
StackBlitz
stackblitz.com › edit › react-tooltip-hover
React Tooltip Hover - StackBlitz
Starter project for React apps that exports to the create-react-app CLI.
🌐
YouTube
youtube.com › watch
How to Show an Element or Text on Hover in React - YouTube
How to Show an Element or Text on Hover in React
Published   February 3, 2024
🌐
anicons
anicons.dev › home › documentation
Documentation - anicons | How to Use Animated React Icons
One of the most common use cases is adding an animated icon to a button. Here's how to make the icon animate when hovering the button: import { useState } from 'react'; import { ArrowRightIcon } from './components/ArrowRightIcon'; function CallToActionButton() { const [isHovered, setIsHovered] = useState(false); return ( <button onMouseEnter={() => setIsHovered(true)} onMouseLeave={() => setIsHovered(false)} style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '12px 24px', fontSize: '16px', border: 'none', borderRadius: '8px', background: '#0070f3', color: 'white', cursor: 'pointer', }} > Get Started <ArrowRightIcon isHovered={isHovered} size={20} /> </button> ); }
🌐
Josh W. Comeau
joshwcomeau.com › react › boop
Boop! A hover animation using React hooks • Josh W. Comeau
November 23, 2020 - Instead, what if the icons only popped over to their hover state for a brief moment? ... I love this effect. It's playful and dynamic and surprising. It's not commonly done, since it's significantly more complex than using transition. It can be used in all kinds of nifty ways. Some examples: ... After an informal social media poll, it was decided that this effect would be called a "boop". In this tutorial—which is intended for intermediate React users—we'll learn how to build it ✨
🌐
Syncfusion
syncfusion.com › react › tooltip
React Tooltip | A Rich Display for Information | Syncfusion
Show the React Tooltip on hover, click, touch, and focus on any element.
🌐
GitHub
github.com › react-icons › react-icons › issues › 60
How can I change icon color based on Hover Active etc pseudo-classes ? · Issue #60 · react-icons/react-icons
October 26, 2016 - I mean is there anyway to set component class because className='' isn;t working with me
Author   outlawshade
🌐
Reddit
reddit.com › r/react › making multiple react icons changing different color on hover using jsx
r/react on Reddit: Making multiple react icons changing different color on hover using JSX
September 10, 2022 -

'm trying to make different icons in the footer, with different brands. I want them to change color when I'm hovering over them. I've created a CSS class with the hover pseudo-class, but I want to make a sort of parameter in my JSX file which tells the class that a certain color should be applied to a certain icon This Is my CSS class:

here's the CSS class:

.icon-background {

color: rgb(49, 45, 44, 0.8);

}

.icon-background:focus,

.icon-background:hover {

background-color: var(--color);

transition-duration: 0.2s;

padding: 2.5px;

}

🌐
MUI
mui.com › material-ui › react-tooltip
React Tooltip component - Material UI
The tooltip is normally shown immediately when the user's mouse hovers over the element, and hides immediately when the user's mouse leaves. A delay in showing or hiding the tooltip can be added through the enterDelay and leaveDelay props.