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>
);
}
}