One way to target a span inside a label element when a checkbox is checked using React Material UI createStyles is by using CSS selectors in combination with

I need help targeting the span element within a checkbox label in order to change its background color when the checkbox is checked.

<div className={classes.container}>
  <input type="checkbox" id="checkboxid" />
  <label className={classes.label} htmlFor="checkboxid">
    <span className={classes.labelText}>Target</span>
  </label>
</div>

container: {
  '& input:checked': {
    '& label': {
      '& $labelText': {
         background: 'red'
      }
    }
  }
}

Answer №1

When the label is not placed inside the input but is a sibling, you can utilize the CSS sibling selector +

In this particular scenario

const useSpanStyles = makeStyles({
    container: {
      '& input:checked + label': {
          '& span': {
              background: 'red'
          }
       },
    },
    label: {},
    labelText: {}
});


export function ComponentXYZ(){

    const classes = useSpanStyles();

    return (
            <div className={classes.container}>
                <input type="checkbox" id="checkboxid" />
                <label className={classes.label} htmlFor="checkboxid">
                    <span className={classes.labelText}>Target</span>
                </label>
            </div>
    );
}

To be honest with you, if you are using MUI you should've utilized their components as they provide an easier way to compose and build UI

Here's my recommendation

function ComponentXYZ(){

const [checked, setIsChecked] = useState(false);

const checkedHandler = useCallback(function _checkedHandler(event: any) {
   setIsChecked(event.target.checked);
}, []);

return (
          <div>
              <FormGroup>
                  <FormControlLabel
                      control={<Checkbox
                          checked={checked}
                          onChange={checkedHandler}
                      />}
                      label={
                          <Typography style={{ background: checked ? 'red' : 'inherit' }}>
                              {'Label That change color'}
                          </Typography>
                      }
                  />
              </FormGroup>
          </div>
);

}

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

Files with extensions containing wildcards will trigger a 404 error when accessed from the public folder in NextJS

I have successfully set up my public folder to serve static files, however I am encountering an issue with files that have a leading dot in their filename (.**). Specifically, I need to host the "well-known" text file for apple-pay domain verification, wh ...

Need to swiftly modify values of css attributes?

Here is a snippet of the code I am working with: <div></div> <button> Go </button> div { width: 50px; height: 50px; border: 1px solid #ccc; } var bgs = ['red', 'blue', 'yellow', 'green&apo ...

Steps to display a JSX component stored in a variable

Presently, I am implementing an if/else statement within my code to determine the content that will be displayed in the JSX element named 'signupMessage'. Subsequently, I render the contents of this 'signupMessage' element. render() { ...

Elevate your website with a mesmerizing CSS effect: watch

I am trying to achieve a CSS3 effect where an image slides up when hovered over, similar to this. I came across this example, but I do not want to use the box's background property. <div class="box"> <img src=image/image.jpg> & ...

Overlay with a progress bar that obscures visibility

I'm dealing with a progress bar that needs to be displayed on top of an overlay. If you take a look at this jsfiddle, you can see the issue. Here's the markup: <div class="overlay mouse-events-off"> <div class="progress progress-st ...

What is the best way to send information from one screen to a flatlist in React Navigation?

Currently, I am retrieving data from an API in the form of a JSON file. My goal is to pass this data from the main app to the appStack and then to the sessionsStack before displaying it on the home page. However, my console logs indicate that the data only ...

Deriving usefulness from TextInput by sending it to a function

I am currently working on a project where the value inputted in a TextInput is passed to a function. My inquiry lies in how I can extract the text value from the searchString that gets sent to the function, as it's currently an object. <TextInput ...

Issue with @reach/router where the URL path is updated but the component fails to render after clicking a Link

I recently switched to using @reach/router for a new project after receiving a recommendation on the react-router-dom GitHub page. Despite what should be a simple use case, I am encountering some issues. Initially, I attempted to integrate the @mui BottomN ...

The buttons within the bootstrap navbar are not properly collapsing or resizing when the screen size is decreased, causing them to overlap and maintain their

As a newcomer to bootstrap, I recently created a navbar with several buttons. However, when I reduce the screen size to 1000 pixels, the button text gets overwritten and the navbar extends off the screen. I don't want the navbar to collapse at this si ...

Vertical Image Alignment in Bootstrap 3

Looking for some help with a basic HTML structure here. I have a single row divided into two columns, each containing an image of the same size. What I need is to center one image both horizontally and vertically in each column. <div class="containe ...

The Axios onDownloadProgress function on the GET method is only triggered one time, and the setTimeout within the callback is never executed

I'm currently working on displaying a progress bar while fetching data from the backend API. However, I've encountered a couple of issues that I'm struggling to resolve. Firstly, the progress bar jumps from 0 to 100 without showing any actua ...

Using JavaScript, aim for a specific element by its anchor headline

I'm looking to make some changes to my navigation menu, specifically hiding the home menu item unless the mobile navigation menu is toggled. Is there a way for me to target the "home" anchor title and apply the active class to it when toggled, similar ...

What is the best way to adjust the width of a textarea based on its content

How can I dynamically set the width of a React Semantic UI textarea based on its content? Setting min-width doesn't seem to be working. Any suggestions? <Textarea key={idx} defaultValue={formattedText} className="customInpu ...

Is it possible to apply styles to javascript elements without relying on img class? Additionally, how can I incorporate an onclick button while maintaining a fully functional navigation bar?

My current project involves creating an interactive collage where users can click around and have pictures pop up at the clicked location. The functionality works as intended, but now I'm facing issues with the navigation bar not being clickable. Addi ...

Having deleted the text area in a React app, I encountered difficulty in re-adding it or including any other options

When the Text Area is clicked, a button should add a relevant text area on a page. By clicking the close button, the system should remove the added textarea in a React page. Initially, the close button should not be displayed. In this particular example, t ...

The React component is failing to display updated data from the Redux store

I've been working with React and Redux, trying to update my counter value in the React view. I can successfully log the latest state of my Redux store, but the changes are not reflecting in my React view. const counter = (state = 0, action) => { ...

The rendering of the font appears distinct when viewed on an iPad compared to when displayed

Visit this website. The menu displays correctly on desktop, but on iPads, the font appears larger leading to a line break. Is it because the selected font isn't loading and defaulting to Times New Roman instead? It seems likely since I experience the ...

What is the process for changing a Supabase user's password within a NextJs application?

Currently, I am encountering difficulties updating a password for a supabase user on a BlitzJs (NextJs) project. The process starts with sending an email containing a reset link. Upon clicking the link, the user is directed to a page where they can update ...

What are the best practices for integrating breakpoints in MUI?

I'm looking to make my project responsive by incorporating MUI breakpoints, but I'm struggling to grasp how to implement them in a straightforward manner. The concept of creating a const styles as outlined in their documentation seems a bit compl ...

Caution: ReactJs reminds you that every child in a list must possess a distinct "key" prop

I'm currently working on a project for managing a contracting company, and part of the requirement is to display all receipts for each user in the company. However, I encountered the following error: Warning: Each child in a list should have a unique ...