skip to Main Content

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;

enter image description here

i tried passing it down as a prop from the parent component but it still gives me the same result

2

Answers


  1. 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:

    const colors = [
      "Slate",
      "Gray",
      "Zinc",...
    ].map(c => c.toLocaleLowerCase());
    
    const Card = ({ icon, title, subtitle }: CardProps) => {
      const clipboard = useClipboard({ timeout: 1000 });
      const color = `bg-${colors[title.length % colors.length]}-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;
    
    Login or Signup to reply.
  2. 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:

    const colors = [
            "bg-slate-500",
            "bg-gray-500",
            "bg-zinc-500",...
        ];
    
    const randomColor = colors[Math.floor(Math.random()*colors.length)];
    .
    .
    .
    <button className={`${randomColor()} p-2`}>...</button>
    

    2)you can use css variables:

        const colors = [
                "#be3455",
                "#f69a92",
                "#621a55",
            ];
    
        const randomColor = colors[Math.floor(Math.random()*colors.length)];
        .
        .
        .
        <button
           className='bg-[var(--customPadding)] p-2'
           style={{ '--customPadding':randomColor}}/><button>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search