In React Is there a way to change the background color of a parent Label tag on a Radio Input checked?

Viewed 1817

I am using React Semantic UI. In css I am trying to change the Background color of a Parent label of an input, so when the radio button is clicked it changes colors. I am hiding the radio button with display none. Since the label gives it a nice button look. Here is my code. In html I just used a input tag and changed the span but it has to be done differently with the react semantic ui library. I was able to get it to work with input and span like in my html version but in this case the click functionality wouldn't work.

Here is a CodeSandbox with the React Semantic Ui Library loaded in its implements the first answer but does not work. https://codesandbox.io/s/kind-tereshkova-u9toz?fontsize=14

I Added the "Compiled" html

<Segment>
    <Menu attached="top" borderless={true}>
        <Menu.Item>
            <Header>
                 Scale:
            </Header>
            <Label className="filter_check" size="large">
                 <Form.Field
                     label="Year"
                     control='input'
                     type='radio'
                     name='year'
                 />
            </Label>
        </Menu.Item>
    </Menu>
</Segment>
.filter_check input {
    display: none;
}
input:checked + .filter_check>.label {
    background: #00b5ad !important;
    width: 100% !important;
}

.field input[type=radio]:checked + label {
    background: red;
    color: #fff;
    margin-left: 1em;
    padding: .3em .78571429em;
}

"complied" html

<div class="ui segment">
   <div class="ui borderless top attached menu">
      <div class="item">
         <div class="ui header">Scale:</div>
         <div class="ui large label filter_check">
            <div class="field"><label><input name="year" type="radio"> Year</label></div>
         </div>
      </div>
   </div>
</div>
1 Answers

After viewing the SandBox, I was able to see that the React code compiles to the following HTML:

<div class="ui large label filter_check">
  <div class="field">
  <label>
  <input name="year" type="radio"> Year
  </label>
  </div>
</div>

Then I figured you want to modify the parent element upon clicking the input field. This is not trivial and required modifying the parent element, which I did using the onChange prop of the <Form.Field>:

<Label className="filter_check" size="large">
    <Form.Field
        label="Year"
        control="input"
        type="radio"
        name="year"
        onChange={checkInput}
    />
</Label>

With the following function, that adds the checked class to the modified element:

function checkInput(e) {
    let labelElement = e.target.parentNode;
    let bgElement = labelElement.parentNode.parentNode;
    bgElement.classList.add('checked');
}

Then we update the CSS with the following:

div.ui.large.label.filter_check.checked {
    background-color: red;
}

And - VoilĂ !

Related