Home > Software engineering >  How to change the color dynamically in reactjs?
How to change the color dynamically in reactjs?

Time:01-26

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} >{item.attstatus} </span> <i onClick={() => modalClick(item.atte_id)} data-bs-toggle="modal" data-bs-target="#exampleModal" ></i> </td>


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

export default Contractor

This is my output

enter image description here

CodePudding user response:

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' }} >{item.attstatus} </span> 
                        <i onClick={() => modalClick(item.atte_id)} data-bs-toggle="modal" data-bs-target="#exampleModal" ></i> 
                    </td>
                </tr>
            </tbody>
        )
    })
}

CodePudding user response:

You can simply create a function for background color

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


<td><span style={{background: getColor(item.attstatus)}} >...
  • Related