Home > Net >  how to change background color of div when radio button inside the div got checked in react?
how to change background color of div when radio button inside the div got checked in react?

Time:09-08

My code looks like this

<div >
<div >
    <input class type="radio" id="Infant" value>
<img src="datarimage/png;" height="25" width="25" alt> 
<label for="Infant" >Infant</label>
</div>
<div >
    <input class type="radio" id="Child" value>
<img src="datarimage/png;" height="25" width="25" alt> 
<label for="Child" >child</label>
</div>
</div>

my requirement is when radio button is checked whole div with class radio-wrapper backgroundcolor should be changed to blue. how to do this?

CodePudding user response:

const [backgroundColor, setBackGroundColor] = React.useState("black")
const [radioButton, setRadioButton] = React.useState(false)
        
function setBackGroundColorFunction(){
setRadioButton((radioButton) => !radioButton)
!radioButton? setBackGroundColor("blue") : setBackGroundColor("white")
 }
        
     
<div  style={{backgroundColor: backgroundColor}}>
<input type="radio" id="Infant" checked={radioButton} onChange={()=> setBackGroundColorFunction()} />
<img src="datarimage/png;" height="25" width="25" alt>
<label for="Infant"  style={{backgroundColor:backgroundColor}}>Infant</label>
</div>

You can do the same process to second radio, label too.

Or add them inside of that then carry style to main div to include all.

CodePudding user response:

You can use the :has() function and the :checked selector in css, like this:

https://developer.mozilla.org/en-US/docs/Web/CSS/:has

https://developer.mozilla.org/en-US/docs/Web/CSS/:checked

.radio-wrapper:has(input:checked){
  background-color: blue;
}
<div >
  <div >
    <input class type="radio" id="Infant" value>
    <img src="datarimage/png;" height="25" width="25" alt>
    <label for="Infant" >Infant</label>
  </div>
  <div >
    <input class type="radio" id="Child" value>
    <img src="datarimage/png;" height="25" width="25" alt>
    <label for="Child" >child</label>
  </div>
</div>

  • Related