I am sending a tailwind color green-500
from the prop bgColor
and then use it inside the after:border-b-${bgColor}
in the positionStyles
object.
But tailwind is unable to dynamically parse after:border-b-${bgColor}
as a tailwind class.
How to solve this issue? I am open to new suggestions or ways to rewrite my code.
What I want is to pass just a color like green-500
and then let tailwind render it as a class.
Following is my code:
const TOOLTIP_POSITIONS = {
TOP: "TOP",
RIGHT: "RIGHT",
BOTTOM: "BOTTOM",
LEFT: "LEFT",
};
const ToolTip = ({
title,
position = TOOLTIP_POSITIONS.BOTTOM,
isOverflowX = false,
noTooltip = false,
zindex,
bgColor = "green-500",
keys = [],
children,
}) => {
const positionStyles = {
[TOOLTIP_POSITIONS.BOTTOM]: `top-[100%] mt-2
after:content-[""]
after:absolute
after:top-[-5px]
after:left-2/4
after:-translate-x-2/4
after:w-0
after:h-0
after:border-l-[6px] after:border-l-transparent
after:border-b-[6px] after:border-b-${bgColor}
after:border-r-[6px] after:border-r-transparent`,
};
return (
<div
className={`tooltip-wrapper group relative flex w-full items-center justify-center font-medium`}
>
{children}
<div
className={`tooltip absolute hidden w-max rounded-lg bg-gray950 p-2 text-center text-white group-hover:flex group-hover:items-center ${positionStyles[position]}`}
>
{title}
</div>
</div>
);
};
2
Answers
As per the documentation:
You could:
Have the entire class in the
bgColor
prop likeHave a dictionary for
color
to Tailwind class names:Use the
style
attribute for truly dynamic colors, iftheme
can be converted to a valid CSS color value (or you could get the color from Tailwind):safelist
the classes, if you have a limited number of known colors:Instead of using
after:border-b-${bgColor}
the whole class name should be variable meaning