简体   繁体   中英

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

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.

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>
      </>
    );
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM