user20658000
user20658000

Reputation:

How to change the color dynamically in reactjs?

I am working in react project and i want to change the color of my present and absent data which is fetched from database.

For this purpose i used conditional statement but i got all green in color. how can i do it or where i am doing it wrong? there are number of solutions in SO but none of them worked for me

import React, { useEffect, useState } from 'react'
import { NavLink, useParams } from 'react-router-dom'
import Navbar from './Navbar';
import { useNavigate } from 'react-router-dom';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';


const Contracter = () => {
    
 
    const [contarctor, setcontarctor] = useState([])
   
    const color = contarctor[0]?.attstatus === "present" ? 'green' : 'red';
    const styles = {  backgroundColor: color };

 const getmemberid = async (PM_id) => {

        try {

            const res = await fetch(`/getattendance/${PM_id}`, {
                method: "GET",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json"
                },
                credentials: "include"
            })

            const result = await res.json()
            setcontarctor(result)
            console.log();

        } catch (error) {
            console.log(error);
        }
    }

    return (
<>
                            {
                                contarctor?.map((item, i) => {
                                    return (
                                        <tbody>
                                            <tr>
                                                <th scope="row">{item.attdate}</th>
                                                <td><span style={styles} class="badge rounded-pill ">{item.attstatus} </span> <i onClick={() => modalClick(item.atte_id)} data-bs-toggle="modal" data-bs-target="#exampleModal" class="bi bi-pencil-square "></i> </td>


                                            </tr>
                                        </tbody>
                                    )
                                })
                                                  
        </>
    )
}

export default Contractor

This is my output

enter image description here

Upvotes: 0

Views: 527

Answers (2)

Ahmad Arif
Ahmad Arif

Reputation: 101

You can simply create a function for background color

const getColor = (status) => {
 return status == 'present' ? 'green' : 'red';
}


<td><span style={{background: getColor(item.attstatus)}} class="badge 
  rounded-pill ">...

Upvotes: 1

0stone0
0stone0

Reputation: 43904

const color = contarctor[0]?.attstatus === "present" ? 'green' : 'red';
const styles = {  backgroundColor: color };

Only checks the first ([0]) index and applies that for all the items.

Remove that, and just set style do it inline in the map():

style={{ backgroundColor: item.attstatus === "present" ? 'green' : 'red' }}

So the final JSX:

{
    contarctor?.map((item, i) => {
        return (
            <tbody>
                <tr>
                    <th scope="row">{item.attdate}</th>
                    <td>
                        <span style={{ backgroundColor: item.attstatus === "present" ? 'green' : 'red' }} class="badge rounded-pill ">{item.attstatus} </span> 
                        <i onClick={() => modalClick(item.atte_id)} data-bs-toggle="modal" data-bs-target="#exampleModal" class="bi bi-pencil-square "></i> 
                    </td>
                </tr>
            </tbody>
        )
    })
}

Upvotes: 1

Related Questions