Modifying Table Cell Backgrounds Based on Value in React Tables

I am currently utilizing reactstrap to design my table and employing axios to interact with my backend data.

The objective is to dynamically change the background color of a cell based on its value. For instance, if the cell value is less than 0.25, it should be green; otherwise, if the value is less than 0, it should be red.

This snippet showcases my existing code structure:


//Input sending data and Calling API back
state = {
  data: []
}

//this gets triggered on line 85
search = e => {
e.preventDefault();
axios.post("/results",{search_question: document.getElementById("buscar").value})
.then((res) => {
const data = res.data
const question = []

for(var i in data)
{question.push(data[i])}
console.log(question)

this.setState({paas:question[1]})
})

}

render() {

const{paas = []} = this.state
return (

<Table>
<thead>
  <tr>
    <th>Question</th>
    <th>Sentiment</th>
    <th>Magnitud</th> 
  </tr>
</thead;
<tbody>

{paas.length ? paas.map(paa => (
  
<tr>
  <td key="Questions" style= {{}}>{paa.Questions}</td> 
  <td key="Sentiment">{paa.Sentiment}</td>
  <td key="Magnitud"> {paa.Magnitud}</td>
</tr>
))
:
(<p> </p>)
}
</tbody>
</Table>) }
</Container>
</div>

Do you think this approach is suitable for displaying tables, or do you recommend an alternative method?

Answer №1

Instead of using conditional statements like if/else, you can utilize a ternary operator to assign a class or value

<td key="Questions" className={value > 0.25 ? 'greenclass' : 'redclass' }>

Alternatively, you can use inline styles for conditional rendering:

<td key="Questions" style={{ background: value > 0.25 ? 'green' : 'red' }}>

Handling multiple classes:

For scenarios involving more than two classes, create an external function with switch cases to determine the appropriate class name.

Define this function outside the render method

resolveClass = (value) => {
    let className = ''

    switch (true) {
        case (value > 0.25):
            className = 'green'
            break;
        case (value < 0):
            className = 'red'
            break;
        default:
            break
    }

    return className
}

Then within the render method, use

<td key="Questions" className={resolveClass(paa.Questions)}>

Answer №2

There are two ways to achieve this:

Method 1: Utilizing a CSS class (recommended):

<td key="Questions" className={(paa.Questions == 'value_to_compare') ? 'css_class': null}>{paa.Questions}</td>

Method 2: Using conditional styling:

 <td style={(paa.Questions == 'value_to_compare') ? {textAlign:'center'}: {}}></td>  // You can customize the style instead of textAlign:'center'

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

Implementing class styles using jQuery; however, certain styles fail to be effectively applied

As a beginner, I am experimenting with applying CSS class styles using jQuery. Specifically, I am trying to set two class attributes: color and font size. Surprisingly, only the color attribute is being applied despite both attributes being defined under t ...

Using setInterval in NextJs with a dynamic time variable in a React useEffect Hook

One of the functions I've created is called fetchData. Its main purpose is to fetch data from an API endpoint and update that data at specified intervals. import { useState, useEffect } from 'react'; export const fetchData = (endpoint, inte ...

The error message "React Native - __DEV__ is not defined" has been

I am working on a project that involves [email protected]. I recently deleted the node_modules folder and then executed the following commands: npm i react-native upgrade However, I encountered the following error: react-native.js:15 ReferenceErr ...

Establish initial content for the specified div area

I need help setting page1.html to display by default when the page loads. Can you provide some guidance? Appreciate your assistance in advance. <head>     <title>Test</title>     <meta http-equiv="content-type" content="tex ...

Utilize alternating colors from the Material UI palette to enhance the appearance of

Can someone help me understand how to utilize the different color variants in Material UI? For instance, the theme primary color has various options like 100, 200, 300, 400, 500, and so on. How can I access these colors from within my component? I attempt ...

Guide on how to use a tooltip for a switch component in Material-UI with React

I am attempting to incorporate a tooltip around an interactive MUI switch button that changes dynamically with user input. Here is the code snippet I have implemented so far: import * as React from 'react'; import { styled } from '@mui/mater ...

The ReactJs Context remains stagnant, with values persisting as their default settings

I have a parent component with a nested React context. Within this parent component, I utilize the useEffect() hook to fetch data from an API and update the context with these values. However, in my child component which consumes the context, the values al ...

Unable to create a flawless circle using Canvas

No matter how hard I try, drawing a perfect circle seems impossible for me. Every time I attempt it, all I manage to create is an ellipse. Check out this code snippet I put together as an example: function canvasClicked(number) { var c = "canvas" + nu ...

Text in the middle of a button

I've been attempting to recreate the design of this "subscribe to the newsletter button". I'm struggling with achieving the white "inside border or outline" effect. Here is an example of the button ...

Issue with ReactJS and Material UI: FlexGrow functionality malfunctioning

I'm currently grappling with the implementation of FlexBox, particularly in understanding how to effectively utilize flexGrow. Despite my efforts, I haven't been able to achieve the desired result as the background appears to only wrap around the ...

Does the component need to be re-rendered every time I visit the page, even if the data remains the same?

I'm trying to grasp the concept of how memo works with components. Here is a simple component that I have, which is static: const Home = memo((props: any) => { useEffect(() => { console.log('home changed'); }, []) ret ...

Tips for halting all YouTube videos in a Reactjs environment

I am currently working with React.js and using Next.js. I have implemented a "YouTube video slider" and now I am looking for a way to stop all videos when a button is clicked. Can anyone provide guidance on how to achieve this? Below is the code snippet ...

Implementing Generic Redux Actions in Typescript with Iterable Types

Resolved: I made a mistake by trying to deconstruct an object in Object.assign instead of just passing the object. Thanks to the assistance from @Eldar and @Akxe, I was able to see my error in the comments. Issue: I'm facing a problem with creating a ...

Automatically updating CSS file in progress

Is there a way to have CSS changes automatically update on my template without requiring me to manually refresh the page? I've noticed this question being asked multiple times, but none of the solutions provided seem to work for me. I attempted usin ...

What is the importance of having Express in the frontend?

As someone who is relatively new to the world of JavaScript and web applications, I recently came across an Express web application project that contained a public directory, client directory, and server directory. This has raised some questions for me. I ...

Why did the bootstrap installation in my project fail?

Previously, everything on my website was functioning correctly. However, upon launching it now, I noticed that the carousel, buttons, and other elements are broken. It seems like there might be an issue with the Bootstrap CDN as the buttons and sliders are ...

The type '0 | Element | undefined' cannot be assigned to the type 'Element'

I encountered the following error: An error occurred when trying to render: Type '0 | Element | undefined' is not assignable to type 'Element'. Type 'undefined' is not assignable to type 'ReactElement<any, any>&apo ...

Sliding panel for horizontal overflow

Currently, I am developing a web animation GUI that requires a sliding timeline area similar to this example: With a starting time of 0, there is no need to slide to negative times, but the ability to zoom in and slide side to side to view the entire time ...

Modifying array elements in JavaScript without explicit instructions

I am relatively new to Javascript and seem to be encountering a rather puzzling issue that I'm unable to resolve. Currently, I have two classes: Country and PPM_Data. The Country class contains parameters such as name, area, ppm, etc., along with a f ...

Comparing attribute selectors to class selectors in the realm of styling

I often come across code that looks like this: <input type="text" class="class1" name="text"> <input type="submit" class="class2" name="submit"> which is then styled as follows: input[type=text] { styles here...} input[type=submit] { sty ...