Is it possible to dynamically adjust the background color of a parent Label element in React when a Radio Input is selected?

Utilizing React Semantic UI presents a challenge when attempting to change the background color of a parent label related to an input element, particularly with a hidden radio button. In this situation, it is important for the label to maintain its button-like appearance. Although similar effects were achieved using standard HTML and CSS, the functionality did not translate seamlessly to the React Semantic UI library.

For reference, a CodeSandbox showcasing the React Semantic UI Library implementation can be accessed here. It should be noted that while the code mirrors previous attempts, the desired result was not achieved.

Below is an excerpt from the code:

<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;
}

The resulting "compiled" HTML is shown below:

<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>

Answer №1

Upon exploring the SandBox, I discovered that the React code compiles into the HTML structure below:

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

I realized that you wanted to make changes to the parent element when the input field is clicked. Achieving this required modifying the parent element, which I accomplished by 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>

I implemented a 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');
}

Next, we updated the CSS as follows:

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

And there you have it - Success!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mastering SVG Path Coordinates using Pure JavaScript

Is it possible to target and manipulate just one of the coordinate numbers within an SVG path's 'd' attribute using JavaScript? For example, how can I access the number 0 in "L25 0" to increment it for animating the path? function NavHalf ...

Transforming a CSV file into JSON format using Gatsbyjs

I am currently exploring the possibilities of GatsbyJs and considering the utilization of the gatsby-transformer-csv plugin. You can find the documentation for this plugin here. I have got my hands on two CSV files exported from WordPress that I am eager ...

Having trouble bypassing the following input field despite setting the tabindex to "-1"

Observing a curious behavior.... In my form, there are multiple input fields. When I handle the "blur" event on the first input and set the "tabindex=-1" on the subsequent input field (inside the blur event handler using $(selector).prop("tabindex","-1"); ...

If no item is found in the array loop, return zero and organize the items as weekdays

I have an array that needs to be displayed in a particular format: "Month" => [ "Week 1" => ["Monday" => 1], "Week 2" => ["Tuesday" => 69, "Wednesday" => 17, "Friday" => 3], "Week 3" => ["Thursday" => 3], "Week 4 ...

Using JQuery selectors to locate elements with or without child elements

Below is a demonstration of HTML code: <div class="container"> <div class="zone"> <img class="thumb" alt="GG"> </div> <div class="zone"> <span>&nbsp;</span> </div> <div cl ...

Module not found in Node.js environment (webpack)

I seem to be encountering an issue with loading any modules. Despite reinstalling my operating system, I continue to face the same error when attempting to use any module. I have tried reinstalling node, clearing the cache, and more. To view the code, pl ...

achieving initial value to show upon page load

I'm trying to set a default value that is visible when the page loads. My goal is to have the first button always displayed by default in the "display-donation" div whenever someone visits the form. Currently, when the page loads, 10 is highlighted ...

incorporating my unique typographic styles into the MUI framework

I'm currently working on customizing the typography for my TypeScript Next.js project. Unfortunately, I am facing difficulties in configuring my code properly, which is causing it to not work as expected. Can someone kindly provide assistance or guida ...

JavaScript Callbacks and Promises: Exploring Asynchronous Programming

For the past 2 days, I've been struggling to figure out my mistake. It seems that I can't get past the "undefined" returned value because I'm having trouble grasping callbacks or promises. Despite reading numerous posts and trying simple exa ...

Combining two states in the Vuex store

In my Vuex store, I have two states: notes (synced notes with the server/DB) localNotes (unsynced notes that will move to 'notes' state upon syncing) To display the notes in a list, I use a getter that merges the two objects and returns the me ...

Different Ways to Conceal a Div Element Without Using Jquery

One interesting feature of my website is that users can select audio from a drop-down box, triggering the $.post function to display an auto-playing audio player in a div. However, I'm facing a problem because I don't want the audio player to be ...

Effortlessly Achieving Full Height Section Scrolling in Vue3

I have two sections, named One and Two, each taking up full-screen height and width (ignoring the top navbar in the video). As a user scrolls through my page, I want to prevent the sections from being partially scrolled. The window should display either ...

Filter an object within an array based on the index values of another array

Imagine a situation where users can select multiple items and remove them. This calls for two arrays: One containing checkbox values (checked status and index) The other holding the actual items that need to be filtered based on the checked values' ...

Troubles with CSS drop down alignment in Internet Explorer 7

I've been racking my brain all morning trying to solve this issue. My current project involves creating a website for a client, and I'm having trouble getting the dropdown menu to position correctly in IE7. It's working fine in all other br ...

Generated serve IDs are having issues when trying to use tabs

I am encountering an issue with my jQuery file jQuery(document).ready(function() { var orderId= <%= OrderLi.ClientID %>; jQuery("#ApprovalTab").css("display", "block"); jQuery("#ApprovalLi").css("background-color", "#5EA8DE" ...

React: State updates are not reflecting in the UI components

I am facing an issue where a function component is not updating visually when the state changes. To illustrate this problem, I have included a simple example of my component in which I update the state but the component does not reflect these changes in t ...

setting width of label and input tags using css

I reviewed some examples here and tried to follow one, but it's not working. Can someone please tell me what I'm missing? fieldset { overflow:hidden; width:90% } label { padding-left:26px; width:250px; display:block; float:left ...

Ensure that the HTML input only accepts numbers and email addresses

Is there a way to restrict an HTML input field to only accept numbers and email IDs? <input id="input" type="text" /> ...

Implementing a Vertical Scrollbar for tbody Using Bootstrap Table Styles

My goal is to display a vertical scrollbar within the tbody. After researching, I found suggestions to apply display:block to both the tbody and thead, as shown here Unfortunately, this solution does not work when the table has Bootstrap's table tabl ...

ng-click not responding when clicking on a programmatically triggered event

I have some experience with jQuery, but I am new to AngularJS. Recently, I encountered an issue when trying to call a function on the click event of a link. When I manually clicked on the link, everything worked fine and the code looked like this: <di ...