Reputation: 75
i have an object of data where i want to change the color of a div on condition base
<Col className="mainbody">
{items.map(data => <CardPanel className="location"
key={data.parkingID}>
<div onClick={() =>
this.handleClick(data.parkingArea)} >
{data.parkingArea}
{data.status == "booked" ? style="color changed to
red" :style= "color changed to red"}
<Icon>directions_car</Icon>
</div>
</CardPanel>)}
here in {data.status} i want to check the condition if status is "booked" then change bgcolor "red"
Upvotes: 0
Views: 5225
Reputation: 904
There are a lot of ways to do so.
In the following code snippets, let's assume the condition is declared beforehand:
const condition = data.status === 'booked';
Style way
<div style={{ backgroundColor: condition ? "red" : "white" }} />
Using double brackets will cause your component to re-render a lot because of the object's reference changing all the time. There are a lot of utilities to prevent that such as fast-memoize.
Class Way
There are several ways to concatenate classNames conditionally, here is one using ES6 :
<div className={[
classNames.card,
...(cond && [classNames.booked])
]}
/>
There are also some libraries such as classnames for the code clarity's sake. I personally use a custom library to be able to write it like this:
<div className={cn.concat(classNames.card, [classNames.booked, cond])} />
In scss, it will allow you to declare your style as this :
.card {
background-color: white;
transition: background-color .2s ease;
&.booked {
background-color: red;
}
}
Upvotes: 2
Reputation: 5363
You can use either inline styles (https://zhenyong.github.io/react/tips/inline-styles.html) Or assign class name for each case and add a css class for that. For the later option, you can use classnames npm pkg (https://github.com/JedWatson/classnames)
Upvotes: 0