Tips for updating the background color of a specific row

I have a piece of code that I am trying to modify with a specific condition. If {row.BB} is less than or equal to 100, I want to change the background color of the row with this value to red. Can someone help me achieve this? The code is linked to a database and uses a JSX file.

    return (
        <>
            <Navigation />
            <Box bg={'white'} w="100%"
                 p={4}
                 m={4}
                 color="black"
                 rounded={'md'}
            >
                     <Table size='sm' variant='striped' colorScheme='gray'>
                         <Thead>
                             <Tr>
                                <Th>A</Th>
                                <Th>B</Th>
                                <Th>C</Th>
                             </Tr>
                         </Thead>
                         <Tbody>
                         {file.map((row, index) => (
                             <Tr key={index}> 
                                 <Td>{row.AA}</Td>
                                 <Td>{row.BB}</Td>
                                 <Td>{row.CC}</Td>
                             </Tr>
                         ))}
                         </Tbody>
                     </Table>
            </Box>
        </>
    );
}

Answer №1

It seems like the 'bg' attribute is being used to set the background color of each row, which is also utilized for the Box component's background color in your code.

<Tr bg={ () => this.getColorOftheRow(row.BB) } key={index}> 
    <Td>{row.AA}</Td>
    <Td>{row.BB}</Td>
    <Td>{row.CC}</Td>
</Tr>

within the component

function getColorOftheRow(value) {
            if (value <= 100)
                return 'red';
            else if (value >= 100)
                return 'green';
                // add more conditions if needed
            else
                return 'white';
        }

Answer №2

It seems like your question is a bit unclear, but if you are looking to modify this specific row <Td>{row.BB}</Td>, there are two approaches you can take:

  1. Utilizing an If-Else block

` {file.map((row, index) => (

if (row.BB <= 100){
    return (
        <Tr key={index} style={{backgroundColor:'red'}}> 
            <Td>{row.AA}</Td>
            <Td>{row.BB}</Td>
            <Td>{row.CC}</Td>
        </Tr>
    )
else {
    return(
        <Tr key={index}> 
            <Td>{row.AA}</Td>
            <Td>{row.BB}</Td>
            <Td>{row.CC}</Td>
        </Tr>
    )}
}
))}

`

  1. If you are familiar with the ternary operator, you can simplify the process: ` { file.map((row, index) => (

     { row.BB <= 100 ? 
     (<Tr key={index} style={{ backgroundColor: 'red' }}> 
         <Td>{row.AA}</Td>
         <Td>{row.BB}</Td>
         <Td>{row.CC}</Td>
     </Tr>)
     : 
     (<Tr key={index}> 
         <Td>{row.AA}</Td>
         <Td>{row.BB}</Td>
         <Td>{row.CC}</Td>
     </Tr>)
     }   
    

    ))}} `

If any of these methods do not work for you, please inform me.

Answer №3

There are various approaches you could take to tackle this issue, but I believe the most straightforward method would be to keep it uncomplicated (especially since you are already utilizing traditional <table> and <td> elements).

You might want to consider implementing something along these lines:

<Tr>
  ...
  <Td bgcolor={row.BB <= 100 && 'red'}></Td>
</Tr>

Please let me know if that suggestion proves effective for your needs.

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

What is the best way to wait for the state to be set before mapping the array

I have some data stored in an array (shown in the screenshot below) that I am trying to map, but I am facing issues accessing it as it is loaded asynchronously. How can I await the data? Is there a way to achieve this within the render function? render() ...

Activate numerous progress bars to animate as the user scrolls beyond the designated anchor point

Check out my website here: I've spent a lot of time working on this site, but I've hit a roadblock when it comes to animating the skill bars. I still want them to animate as users scroll past a certain point, but I'm struggling to figure it ...

Enhance numerous items within an array of objects within MongoDB

I have a MongoDB collection that resembles the following schema: { "id": "1234657980", "company": "samsung", "models": [ { "name": "A1", "processor": &qu ...

Format the date using moment() for the last week of the current year and return it with the year. Next year's

I encountered an unusual problem when using Moment.js with Angular.js. When I use the .toISOString() method, I get the correct date, but when I use the .format() method, the date is completely wrong. Here is an example to illustrate the issue: Code snip ...

Is it possible to upload a file in Node directly to a stream without the need to first save it to a temporary

Is there a way to directly stream Node.js file uploads to a remote server or fileshare without saving them as temp files on my server first? I am currently using formidable, but it seems to always save the file locally before uploading. It would be more ef ...

The compilation process encountered an error: TypeError - Unable to access property 'exclude' as it is undefined (awesome-typescript-loader)

After successfully converting my existing Angular 2 project into Angular 4, I encountered the following error: Module build failed: TypeError: Cannot read property 'exclude' of undefined For more details, please refer to the attached image bel ...

Distinct vertical menus with varying widths but sharing the same CSS code for the submenus

How can I create a vertical menu bar with submenus on the right side? The first submenu appears correctly, but the second one is narrower than the first. It seems like they have the same code, yet they look different. Below is the HTML code: <div clas ...

Most effective method for converting a table of data to TypeScript

Searching for an effective method to map a table of enum (or interface) data to the correct location. https://i.sstatic.net/5hF2q.png For instance, Smoke Sensor - Push Button can only be linked to SS - PI SYMBOL and Smoke Sensor - PushButton can only be ...

A guide to retrieving JSON data with Javascript

I'm in the process of building a small website for weather forecasting. However, I've encountered an issue when trying to retrieve JSON data from accuWeather - I'm not getting any response. I've double-checked my request and it seems to ...

Having trouble organizing a list of objects based on changing keys

Below is the implementation of a custom pipe designed to sort records: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'sortpipe' }) export class SortPipe implements PipeTransform { transfor ...

The spacing within the table's <tr> elements does not get altered

I am struggling to add a small space in the table <tr> but my attempts have not been successful. How can I resolve this issue? Please refer to the image below for clarification: https://i.sstatic.net/HXdhq.png .panel-booking .panel-body { pad ...

The pictures are not showing up in the photo album

I am currently in the process of building a swim image gallery inspired by the Flex Panel Gallery project from Javascript30 (Repo Link). Upon previewing the site in a browser, I encountered an issue where the images extend beyond the frame, leaving only t ...

Dealing with API responses in Angular 2

Hello there! I am a beginner in Angular 2 and might ask some basic questions, so please bear with me. I am struggling to understand how to handle an API response. Below is my NodeJS Server API function (which has been checked and is working fine): router ...

Why does the ReactJS MaterialUI Modal fail to update properly?

Recently, I encountered a curious issue with my Modal component: https://i.stack.imgur.com/dkj4Q.png When I open the dropdown and select a field, it updates the state of the Object but fails to render it in the UI. Strangely, if I perform the same action ...

What is the correct way to superimpose an image with a transparent background?

I am currently working on a mini game that involves overlaying images on camera views. The goal is to have the gun displayed without the background rectangle, as shown in this image: https://i.stack.imgur.com/yU4A2.jpg The code snippet below is relevant ...

Ensure that the jQuery ajax function triggers only after the images or iframes have completely loaded

I am currently in the process of creating an online portfolio. My goal is to have project information load into the current page via ajax when a user clicks on a specific project. However, I am facing an issue with the timing of the load() success function ...

Clicking on a marker in Google Maps will display the address

I have a map that contains several markers, each designated by their latitude and longitude coordinates. I would like to be able to see the address associated with each marker when I click on it. However, I am currently experiencing an issue where nothing ...

Interacting with Vue3 List Items by Manipulating the HTML DOM

I am currently using Vue 3 and I have a requirement to manipulate a specific list item when a button is clicked. Below is the HTML code snippet: <socialDiv v-for="(follower, i) in followerList" :key="follower.id" :ref="el => ...

Guide to smoothly scroll to a specific Label using GSAP's scrollTrigger and scrubbing within a Timeline

Currently facing an issue with a scrollTrigger Timeline where I need a button to scroll to a specific position. I attempted using seek but it did not work, and even the ScrollTo plugin lacks support for this functionality. The Timeline created using gsap ...

Displaying results of data from a cross domain request

I have some test code related to WordPress displayed below. jQuery(document).ready(function($) { var link = 'http://000.00.00.00/cgi-bin/test.cgi'; $("#sub").click(function() { $.ajax({ type:'POST', url: link, ...