Home > database >  How can I change the background color based on a value?
How can I change the background color based on a value?

Time:11-11

I'm learning React and this question came up. Can I change the background color depending on the variable value that came as a prop?

thanks

import React from 'react';

import "./Card.css"
const card = ({taskObj, index }) => {

    const colorTest = () => {
        let color
        if(taskObj === "JavaScript") {
            color = "red";
        } else {
            color = "Yellow";
        }
    }

    return (
        <>
            <div className="card-wrapper mr-5">
                <div className="card-top card-todo" style={{"background-color": color}} ></div>
                <div className="task-holder">
                <span className="card-header">{taskObj.Name}</span>
                <p>{taskObj.Description}</p>

                    <div className="svg-card">
                        <i className="far fa-edit svg mx-4"></i>
                        <i className="fas fa-trash-alt svg"></i>
                    </div>
                </div>
            </div>
        </>
    );
};

export default card;```

CodePudding user response:

Hey ty using style={{'backgroundColor': color }}. Also add variable inside card component like this: const color = taskObj === "JavaScript" ? 'red' : yellow. You will get component that looks like this:

import React from 'react';

import "./Card.css"
const card = ({taskObj, index }) => {

    const color = taskObj === "JavaScript" ? "red" : "yellow";

    return (
        <>
            <div className="card-wrapper mr-5">
                <div className="card-top card-todo" style={{"backgroundColor": color}} ></div>
                <div className="task-holder">
                <span className="card-header">{taskObj.Name}</span>
                <p>{taskObj.Description}</p>

                    <div className="svg-card">
                        <i className="far fa-edit svg mx-4"></i>
                        <i className="fas fa-trash-alt svg"></i>
                    </div>
                </div>
            </div>
        </>
    );
};

export default card;

CodePudding user response:

you can do like this:

...
style={{"backgroundColor": `${taskObj === "javascript" ? 'red' : 'yellow'}`}}
...
  • Related