Home > other >  Why a few this same components works differently in react?
Why a few this same components works differently in react?

Time:01-09

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?

CodePudding user response:

You can use style attribute on react component

<div className={styles.text_container} style={{backgroundColor: isChecked? #a81616 : #000}}>

your code doesnt work, because ID is supposed to be unique and you are only selecting first occurence... if you want to work with DOM in react, dont use getElementByID and use useRef() from react. Its more "reactish" way how to do it.

  •  Tags:  
  • Related