I have recently developed a react component tooltip that is designed to appear based on the direction (top, bottom, left, right) specified in the component parameters. Interestingly, when top or bottom is selected, the tooltip functions perfectly. However, if left or right is chosen, the tooltip ends up appearing within the element it is meant for rather than beside it.
React Component
import React, { useState } from "react";
import styles from "./toolTip.module.css";
const ToolTip = ({
delay,
direction,
content,
children
}: {
delay?: number;
direction: "top" | "right" | "left" | "bottom";
content: any;
children: any;
}) => {
let timeout: any;
const [directionClass] = useState(styles[direction]);
const [active, setActive] = useState(false);
const showTip = () => {
timeout = setTimeout(() => {
setActive(true);
}, delay || 400);
};
const hideTip = () => {
clearInterval(timeout);
setActive(false);
};
return (
<div
className={styles.toolTipWrapper}
onMouseEnter={showTip}
onMouseLeave={hideTip}
>
{children}
{active &&
<div className={`${styles.toolTip} ${directionClass}`}>
{content}
</div>}
</div>
);
};
export default ToolTip;
CSS Styles
.toolTipWrapper {
display: inline-block;
position: relative;
}
.toolTip {
position: absolute;
border-radius: 4px;
left: 50%;
transform: translateX(-50%);
padding: 6px;
color: rgb(217, 212, 212);
background: black;
font-size: 14px;
font-family: sans-serif;
line-height: 1;
z-index: 100;
white-space: nowrap;
}
.toolTip::before {
content: " ";
left: 50%;
border: solid transparent;
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.toolTip.top {
bottom: 100%;
margin-bottom: 2px;
}
.toolTip.bottom {
margin-top: 2px;
}
.toolTip.left {
right: 100%;
margin-right: 2px;
}
.toolTip.right {
left: 100%;
margin-left: 2px;
}