Pranav
Pranav

Reputation: 1646

How to change background color of active radio button in react-bootstrap?

In a React project I've radio buttons enlisting calendar dates and days. My intention is to change the background color of those radio buttons and also persist it. It should not fade away when clicked on screen.

The following is the code for reference:

{newDate.map((data, i) => (
          <ButtonGroup toggle style={{ width: "100%" }}>
            <GridListTile style={gridListStylePhoto}>
              <h5>{currday(data.getDay())}</h5>
              <ToggleButton
                key={i}
                type="radio"
                active="true"
                variant="light"
                name="radio"
                value={currday(data.getDay()) + " " + data.getDate()}
                checked={radioValue === data.getDate()}
                onChange={(e) => {
                  handleChange(e);
                }}
              >
                <br />
                {data.getDate()}
              </ToggleButton>
            </GridListTile>
          </ButtonGroup>
        ))}

Below is the styling reference:

input[type="checkbox"],
input[type="radio"] {
  display: none;
}
.btn-light {
  background-color: transparent;
  border: transparent;
}

.btn-light:checked {
  background-color: red // Here is color doesn't change
}

What could be done in order to change the background color of above radio buttons?

Please refer to the below Codesandbox link.

Codesandbox Link: https://codesandbox.io/s/material-demo-forked-hcbxl

Upvotes: 1

Views: 4416

Answers (1)

nad
nad

Reputation: 1100

You can toggle the class for each radio button using your existing onChange event.

const handleChange = (e) => {
    const newData = e.target.value;
    var elems = document.querySelectorAll(".toggleButtonNew.active");
    [].forEach.call(elems, function (el) {
      el.classList.remove("active");
    });
    e.target.closest("label").classList.toggle("active");
    setRadioValue(newData);
};

And add your desired styles to that class

.active {
    background-color: red !important;
}

Upvotes: 2

Related Questions