Home > other >  How to change background color based on a value with NextJS and TailwindCSS?
How to change background color based on a value with NextJS and TailwindCSS?

Time:07-28

I have a table that displays values from my API. I am wanting to change the background of the Status Field based on the value received for request.status

I have a total of 4 status values

  • Completed
  • Work in Progress
  • To be Started
  • Awaiting Customer Confirmation

What would be the best way to go about this?


export default function RequestPage() {
    const [requests, setRequest] = useState([]);

    useEffect(() => {
        const fetchRequests = async () => {
            const res = await fetch('/api/requests');
            const data = await res.json();
            console.log(data);
            setRequest(data);
        };
        fetchRequests();
    }, [setRequest]);

return (
{requests.map((request) => {
return (
<span aria-hidden="true" className="absolute inset-0 opacity-50 rounded-full bg-green-200"></span>
<span className="relative">{request.status}</span>
)}
})

I am using Typescript. This is the first Typescript project I have done.

CodePudding user response:

You could define a bgColor variable representing the class for the background color and change it based on the request.status:

{
  requests.map((request) => {
    let bgColor = '';
    switch (request.status) {
        case 'Completed': 
            bgColor = 'bg-green-200';
            break;
        case ...
    }
    return (
      <>
        <span
          aria-hidden='true'
          className={`absolute inset-0 opacity-50 rounded-full ${bgColor}`}
        ></span>
        <span className='relative'>{request.status}</span>
      </>
    );
  });
}
  • Related