Sorry if the way I posted this question is dumb. Im not great at explaining things
The code structure looks somewhat like this
function RenderOptions() {
return allOptions.map((val) => {
return (
<>
<label htmlFor={val}>
<input
type="radio"
name="options"
id={val}
value={val}
className="check-btn"
/>{" "}
<span className="text-inner">{val}</span>
</label>{" "}
</>
);
});
}
Didnt put a div since I didnt want to spend some time finding how to align the buttons in rows.
CSS
.check-btn {
opacity: 0;
position: relative;
top: 2px;
}
label {
border-radius: 10px;
font-family: Inter;
font-style: normal;
font-weight: 600;
font-size: 12px;
line-height: 12px;
text-align: center;
width: 100%;
transition: 0.3s ease;
background: #f5f7fb;
border: 0.794239px solid #4d5b9e;
box-sizing: border-box;
border-radius: 7.94239px;
padding-top: 5px;
padding-bottom: 5px;
padding: 5px 10px 5px 10px;
}
label:hover {
background-color: #d6dbf5;
cursor: pointer;
}
.text-inner {
position: relative;
right: 10px;
}
im trying to change the background color of the parent label when the radio button is checked. Can do it the css way or react way provided, only 1 button from each sets color changes .
and if another option is clicked ->
Thanks!
CodePudding user response:
You could do that with CSS or the style prop in React.
I'm assuming your storing the state of the radio buttons somewhere?
When you map through the array, you can check if the current radio button's value is equal to the value of the current state. If they are the same, you can add the class or style to style the label.
CodePudding user response:
TL;DR. See the CodePen sample I prepared for you here, and the snippet below.
In this example, I simply used the useState
hook to keep track of the current radio selection, and applied its value as data
attribute to label
tag. Then you can use CSS to style it as needed.
const App = () => {
const [chosenOne, setChosenOne] = React.useState();
const list = ["Alec Baldwin", "Bruce Willis", "Dwayne Johnson", "Jamie Fox"];
return (
<div>
{list.map((person, i) => (
<label key={i} htmlFor={person} data-chosen={chosenOne === person}>
<input type="radio" name="options" id={person} value={person} className="check-btn" onChange={(e) => setChosenOne(e.target.value)}/>
<span className="text-inner">{person}</span>
</label>
))}
</div>
)
}
.check-btn {
opacity: 0;
position: relative;
top: 2px;
}
label {
border-radius: 10px;
font-family: Inter;
font-style: normal;
font-weight: 600;
font-size: 12px;
line-height: 12px;
text-align: center;
width: 100%;
transition: 0.3s ease;
background: #f5f7fb;
border: 0.794239px solid #4d5b9e;
box-sizing: border-box;
border-radius: 7.94239px;
padding-top: 5px;
padding-bottom: 5px;
padding: 5px 10px 5px 10px;
}
label:hover, label[data-chosen="true"] {
background-color: #d6dbf5;
cursor: pointer;
}
.text-inner {
position: relative;
right: 10px;
}
label label {
margin-left: .5rem;
}