Changing the background color dynamically with NextJS and TailwindCSS based on a specific value

I'm currently working with a table that fetches values from an API. My goal is to dynamically change the background color of the Status Field based on the value received for request.status

There are a total of 4 status values:

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

What would be the most effective approach to achieve 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>
)}
})

This project is my first time using Typescript and I am excited to learn more about it.

Answer №1

To dynamically change the background color of a component based on the request status, you can create a variable named bgColor and update it accordingly:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript obtain scroll position of a child element

I have a setup that looks something like the following: <div> <div id="scrollID" style="height:100px;"> content here </div> </div> <script> document.getElementById("myDIV").addEventListener("touchstart", m ...

Adjust column content to fit width, instead of setting width to 100%

To create columns for the ul, I used flex-direction: column and flex-wrap: wrap. When the elements within the ul are split into multiple columns, each column takes on the width of the widest content in that column. However, if there is only one column, it ...

Tips for centrally zooming responsive images without altering their dimensions

I have created a custom jQuery and CSS function that allows an image to zoom in and out on mouseover while maintaining a constant box size. I modified an example code to suit my needs. Check out the demo here: https://jsfiddle.net/2fken8Lg/1/ Here is the ...

Encountering an error of incorrect format while attempting to ssh into an Azure NextGen VM created by P

Having some trouble creating and sshing into a virtual machine using the Azure nextgen Pulumi API on my Windows 10 machine. After successfully creating the VM, I export the private key to a file for testing purposes. I then adjust the permissions to preve ...

Results don't align with search parameters

const searchClientes = (event) => { if (event.target.value === '') { getClientes(); return; } else { const searchTerm = event.target.value; const filteredClients = clientes.filter(cliente => { return cliente.nome ...

The div within the button is failing to properly adjust to height settings

Check out this Fiddle I'm currently working on a social thumbs up button and I've encountered some challenges. In my button design, I have included a second div to accommodate the right side of it. However, despite trying to adjust its height us ...

Eliminate all HTML code between two specific markers

Is there a way to effectively delete all the HTML content located between two specific strings on a webpage, regardless of their positions and the content in between them? For example, <div class='foo'> <div class='userid'& ...

Is the row border camouflaged by the background?

feed_page: { margin: 'auto' }, feed_list: { margin: 'auto' }, feed_item: { textAlign: 'center', backgroundColor: '#fff', borderBottom: '1px solid #e0e0e0', margin: '10 ...

Developing React components with Typescript requires careful consideration when defining component props, especially when the component may be

Consider the following scenario: { this.props.userName && <UserProfile userName={this.props.userName} /> In the UserProfile component: interface UserProfileProps { userName: string; } class UserProfile extends React.Component<UserProfile ...

What is the best way to restrict users from accessing more than 5 Bootstrap Tab-Panes at once?

Users are restricted to opening only a maximum of 5 tab panes, even if there are multiple tab buttons available. If the user tries to click on the 6th tab, an alert message will be displayed. function addTab(title, url){ var tabs=$(".tabs"), tab ...

Can a HTML submit button be styled with multiple colors?

One of my clients recently requested a submit button with 2 words and 3 different text colors: <input type="submit" value="SUBMIT NEWSLETTER" /> The color scheme for the text is as follows: SUBMIT = black, NEWS = black, LET = white, TER = black. I ...

Opacity property in CSS does not have any impact on the child elements

Similar Question: how do I prevent opacity from affecting child elements? Can CSS or jQuery be used to apply transparency or opacity to an element without affecting its children? ...

Tips for aligning a Twitter button and a regular button side by side on a horizontal

I have two buttons - one for Twitter and the other a normal submit button. I am struggling to align them horizontally on the same line. After experimenting with various combinations of margin settings for ".buttonLine", ".twitter-share-button", and "#newQ ...

Using TypeScript with Vue to Retrieve Information from a Form

Currently, I am attempting to retrieve data from a form in Vue using TypeScript. However, when declaring the data that I intend to use with this form, it seems to be posted on the fields as shown in this screenshot: message getting posted. I am unsure ho ...

Issue with Redux Provider in Next.Js 13 displaying incorrect data from the store

Currently, I am experimenting with Next.Js 13 and encountering some unusual behavior with the redux provider. Instead of observing my slices of state as expected, I am seeing objects named tree, cache, prefetchCache, pushRef, focusAndScrollRef, and canon ...

Retrieve a specific data point from a web API using Angular framework

Objective: How can I retrieve the specific value "test" in Angular? Issue: An error message is being displayed. Error: SyntaxError: Unexpected token e in JSON at position 1 at JSON.parse () Which syntax element am I missing? ASP.NET // Retrieve "tes ...

Label the image with unique div elements that will remain attached to the image

I am attempting to tag some divs onto an image that remains in the correct position as the window size changes. My current setup is somewhat functional, but the markers only stay aligned with the image until it loses height. How can I modify my code to en ...

Issues with Google fonts not displaying properly on WordPress site

I'm just starting out with Wordpress and I'm using the html5blank theme to bring in my stylesheets. However, I've run into an issue where the google fonts are not being applied on my wordpress site. In my header.php file, I have included th ...

I am attempting to link my Firebase real-time database with Cloud Firestore, but I am encountering import errors in the process

I am currently working on enhancing the online functionality of my chat app by implementing a presence system using Firebase Realtime Database. Here is the code snippet that I have created for this purpose: db refers to Firestore and dbt refers to the Rea ...

What is the best way to arrange this script?

I am currently working on a Javascript script that automatically scrolls down and loads a new URL when it reaches the bottom of the page. However, I would like to add a delay of 30 seconds before the new URL is loaded. Although I am relatively new to Java ...