I have the following component named Card:
<article className={styles.card_container}>
<input type="checkbox" className={styles.checkbox} onClick={setCheckbox}/>
<div className={styles.text_container} id="txt_container">
<span>
{props.number}
</span>
</div>
</article>
Which should display checkbox, without the tick – container to check or not, with background colors, depends on this checkbox is checked or not.
For example, when unchecked this should has red color, but when checked – black.
For this, I decided to use state:
const [isChecked, setChecked] = useState(false);
const setCheckbox = (e) => {
if (isChecked===true){
setChecked(false);
document.getElementById("txt_container").style.backgroundColor="#a81616";
}else {
setChecked(true);
document.getElementById("txt_container").style.backgroundColor="#000";
}
}
I wanted to create a few this type of components so I decided to map this with information from array:
{data.map(element=>
<Card number={element.option} key={element.option}/>)
}
(Where data is an array with object with numbers, Card is created components with code above).
The problem is that, when I “check” other components, it change color only at first.
Why did it happen? I appreciate for any help.
And there some css code:
.card_container {
position: relative;
width: 60px;
height: 45px;
margin: 5px;
float: left;
border: 2px solid #50bcf2;
box-sizing: border-box;
}
.text_container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
line-height: 25px;
transition: .5s ease;
}
.checkbox {
position: absolute;
top: 0;
left: 0;
width: 60px;
height: 45px;
opacity: 1;
cursor: pointer;
}
I would like to do this by js, is there other way to do this (not by css)? Or maybe can I inject background color provided by props from for example an array to Card component?