I am trying have random color generator which generates a random color and then pass it onto a prop of card
Even though the css is being applied but i still cannot see the effect of the color.
import { useClipboard } from "@mantine/hooks";
import { IoMdShareAlt } from "react-icons/io";
import { MdDone } from "react-icons/md";
import "./page.css";
import { useEffect, useState } from "react";
interface CardProps {
icon: string;
title: string;
subtitle: string;
}
const Card = ({ icon, title, subtitle }: CardProps) => {
const clipboard = useClipboard({ timeout: 1000 });
const [color, setColor] = useState("");
const colors = [
"Slate",
"Gray",
"Zinc",...
];
useEffect(() => {
setColor(
`bg-${colors[title.length % colors.length].toLocaleLowerCase()}-500`,
);
}, []);
return (
<div className="relative m-6 flex w-[300px] flex-col font-[--font-roboto] font-bold shadow">
<div className="h-[70%]">
<img src={icon} className="h-full w-full" alt={title} />
</div>
<div className="relative">
<button
onClick={() => clipboard.copy("Hello, world!")}
className={`absolute right-5 grid aspect-square h-10 translate-y-[-50%] place-items-center rounded-full ${color}`}
>
{clipboard.copied ? (
<MdDone size={25} color="white" />
) : (
<IoMdShareAlt size={25} color="white" />
)}
</button>
<div className="p-6">
<h3>{title}</h3>
<h4 className="font-light">{subtitle}</h4>
</div>
</div>
</div>
);
};
export default Card;
i tried passing it down as a prop from the parent component but it still gives me the same result
2
Answers
The
colors
appear to be static values, and presumably the titles are not changing often, I don’t see any point in storing a color in state since it is a trivial to compute the string. Compute the color value so it’s available on the initial render. See if this resolves any rendering issues working with Tailwind.Example:
To apply the tailwind style, you must import its classes completely.
so you can consider two solutions for using dynamic classes:
1)Use the full name of the tailwind classes in the desired conditions:
2)you can use css variables: