Currently, I am developing a React form where my goal is to dynamically change the background color of a label when a radio button is selected. However, upon clicking or checking the button, it seems that the state needs to be updated first before displaying the desired background color.
To handle this functionality, I am utilizing a combination of onChange and checked attributes to maintain the state of the radio buttons.
In my quest for answers, I even consulted Chat-GPT, but unfortunately, it didn't provide me with the correct solution.
Below you will find the code snippet for the Task component along with its associated CSS styling:
import React, { useState } from 'react';
export default function Task() {
let [formData, setformData] = useState({
uName: '',
uGender: '',
uMedals: 0,
});
let handleForm = (e) => {
let { name, value } = e.target;
e.preventDefault();
if (name === 'uMedals') {
value = parseInt(value);
if (value <= 0)
value = 0;
if (value > 20)
value = formData.uMedals;
}
setformData((formData) => ({
...formData,
[name]: value,
}));
};
return (
<div className='parent-container'>
<div className='content-wrapper'>
<div className='left'>
<form className='form-wrapper'>
<div className='name-wrapper'>
<label>Name</label>
{/* Name input */}
</div>
<div className='toogle-wrapper'>
<label className='lbl-gen'>Gender</label>
<div className='wrapper'>
<div className='custom-input'>
<input
type='radio'
id='female'
name='uGender'
value='female'
onChange={handleForm}
checked={formData.uGender === 'female'}
/>
<label htmlFor='female'>Female</label>
</div>
<div className='custom-input'>
<input
type='radio'
id='male'
name='uGender'
value='male'
onChange={handleForm}
checked={formData.uGender === 'male'}
/>
<label htmlFor='male'>Male</label>
</div>
</div>
</div>
<button style={{ width: '320px' }}>Add</button>
</form>
</div>
</div>
</div>
);
}
Here is the corresponding CSS code for the above Task component:
.custom-input input[type=radio] {
display: none;
}
.custom-input label {
display: block;
padding: 6px 8px;
color: #fff;
font-weight: bold;
text-align: center;
transition: all 0.4s ease;
cursor: pointer;
border-radius: 4px;
background-color: #717762;
}
.custom-input input[type='radio']:checked + label {
background-color: #f5f5f5;
color: #000;
}