简体   繁体   中英

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

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;```

Hey ty using style={{'backgroundColor': color }} . Also add variable inside card component like this: const color = taskObj === "JavaScript" ? 'red' : yellow 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;

you can do like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM