I've been attempting to dynamically assign classes to radio buttons, but I'm facing difficulties in doing so. I'm trying to create a switch with radio buttons for "ENABLED, PENDING, DISABLED". Based on the selected radio button, I want to change the color by assigning class names. Any assistance on this issue would be greatly appreciated.
For reference, you can view my sandbox at: https://codesandbox.io/s/complex-logic-to-map-an-array-rkspo
App
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
switchValue: "pending"
};
this.handleButtonChange = this.handleButtonChange.bind(this);
}
handleButtonChange(event) {
this.setState(
{
switchValue: event.target.value
},
() => {
console.log(this.state.switchValue);
}
);
}
render() {
const { switchValue } = this.state;
return (
<div className={"switch-toggle"}>
<input
type="radio"
onChange={this.handleButtonChange}
name={"disabled"}
value={"disabled"}
checked={switchValue === "disabled" ? true : false}
/>{" "}
<label className={switchValue === "disabled" ? "switch-red" : ""}>
DISABLED
</label>
<input
type="radio"
onChange={this.handleButtonChange}
name={"pending"}
value={"pending"}
checked={switchValue === "pending" ? true : false}
/>{" "}
<label className={switchValue === "pending" ? "switch-pending" : ""}>
PENDING
</label>
<input
type="radio"
onChange={this.handleButtonChange}
name={"enabled"}
value={"enabled"}
checked={switchValue === "enabled" ? true : false}
/>{" "}
<label className={switchValue === "enabled" ? "switch-green" : ""}>
ENABLED
</label>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
CSS
.switch-toggle {
float: left;
background: #242729;
}
.switch-toggle input {
position: absolute;
opacity: 0;
}
.switch-toggle input + label {
padding: 7px;
float: left;
color: #fff;
cursor: pointer;
}
.switch-pending {
background: grey;
}
.switch-disabled {
background: red;
}
.switch-enabled {
background: green;
}