How can I style radio input elements with CSS when using Material UI within a component?

When styling in CSS, I typically use

input[type="radio"]:checked { color: #000}
, however this expression is not valid in Material UI.

In Material UI, I create rules using makeStyles like so:

const useStyles = makeStyles(() => ({ text: { color: "red", }, }));

Is there a way to target input[type="radio"] elements using makeStyles in Material UI?

Answer №1

If you want to target checked radio buttons, you can use "&:checked" when using the native input DOM component. However, if you are using the MUI <Radio/> component, you should target the rule name checked. You can refer to the documentation for more information.

const useStyles = makeStyles({
  customRadio: {
    "& + label": {
      color: "green"
    },
    "&:checked + label": {
      color: "red"
    }
  }
})

function App() {

  const classes = useStyles();

  return (
    <div>
      <div>
        <input className={classes.customRadio} type="radio" id="foo" name="test" value="foo" defaultChecked={true} />
        <label htmlFor="foo">foo</label>
      </div>
      <div>
        <input className={classes.customRadio} type="radio" id="bar" name="test" value="bar" />
        <label htmlFor="bar">bar</label>
      </div>
    </div>
  );
}

ReactDOM.render(<App/>, document.getElementById("root"));
<body>
  <div id="root"></div>

  <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  <script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>

  <script type="text/babel">
    const { makeStyles } = MaterialUI;
  </script>
</body>

Answer №2

Did you give this approach a shot?

const customStyles = makeUseOfTheme(() => ({ text: { color: "blue", }, 'input[type="checkbox"]:checked': { color: '#333' } }));

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

Implementing dynamic input elements in React components and managing state changes

I am currently working on a React component that includes simple input fields to track state for an AJAX call. There is also a button that, when clicked, generates a new set of input fields identical to the original ones. As a React novice, I initially at ...

Executing the GetDoc function multiple times in a React application

Utilizing Firebase for Authentication & Storage and incorporating useContext from react to encase my application with an authentication layer. After retrieving the user from the authentication layer, I proceed to fetch the user's details from Firesto ...

Click on the link within the Checkbox label on MUI

I am working on creating a checkbox for the "Terms of Use," using FormControlLabel to nest a Checkbox. However, I also need to include a link that opens a Dialog component displaying the terms. The challenge is that clicking on the link checks the checkbox ...

It is necessary for ReactJS eslint rules to employ destructuring when assigning state

class MyDrawer extends Component { const modalOpen = this.state; // Initialize state in the constructor render() { return ( <div> <Drawer modal open={this.state.modalOpen} // <-- this line show error ...

Attach the keyboard to the screen in a fixed position

How can I keep the keyboard always visible on the screen? The screen contains: one TextInput (multiline) two FlatList Typing in the TextInput is fine, but when interacting with the FlatList, the keyboard disappears. I want the keyboard to remain visib ...

Move a single <div> element according to the screen resolution

I'm a beginner in coding and struggling with a specific problem. I need to adjust the position of a container based on screen size. For large and mid-sized screens, the container needs to be left-justified with a small amount of padding from the left ...

Interactive planetary visualization using three.js in real-time

As I work on my react project, I'm developing a globe and looking to initialize it accurately with respect to a specific time, whether it be the current time or a future time. The goal is for this globe to correctly align itself with the day and night ...

Unable to access state as props in React Redux mapStateToProps

Recently delving into the world of react and redux, I'm puzzled by the inability to access the state using this.props within a functional component. Store I define the initial state for rotation and pass it to the store upon its creation. import { ...

Height of the div dynamically increases upwards

Just a quick question - is there a way to make position: fixed divs at the bottom of an element (such as the body) grow upwards as content is dynamically added? Maybe something like anchor: bottom or increase: up? I'm thinking that using JavaScript m ...

Can MobX storage be initialized with data during the initial loading phase?

I am in the process of creating a straightforward Next.js website that contains numerous components nested deep within each other, all utilizing the same set of data such as article names, project names, and FAQ card details. As per the documentation, it ...

Is there a way to automatically deselect the checkbox in the selectableRows of mui-datatables when there are no data rows present?

When there is data, everything works smoothly. However, when there is no data, it gets selected by default. Below is the code snippet for the options: const options = { selectableRows: "multiple", //selectableRowsOnClick: true, rowsSelected: thi ...

Boosting Your Theme - Eliminating Redundant Styles

Currently, I am facing more of a best practice issue rather than a coding one. I am in the process of creating a custom bootstrap theme inspired by https://github.com/HackerThemes/theme-kit. Although I have a functional theme that I am satisfied with, I am ...

Switching from constructors to Hooks in REACT

I am currently working on adding a modal example within a function in my project. I have a specific requirement to incorporate hooks instead of using the constructor in a class-based component. This is the code snippet with the class-based implementation: ...

Navigational elements sporadically spaced apart

My goal is to design a navigation bar for my project, but I am facing an issue where random lines show up between the navigation elements. Here is an example of what I am experiencing: https://i.sstatic.net/UHI89.png If you would like to view the project, ...

Is it considered acceptable to invoke an asynchronous function that retrieves initial data within the constructor of a JavaScript class?

Currently, I am working on a sample application using Mobx and Mobx React Lite to gain a better understanding of this state management tool. When a user accesses the page, the app should load questions. I have some doubts regarding whether it is advisable ...

Concealing items in a loop using Javascript

I need assistance with this issue. I am trying to hide text by clicking on a link, but it doesn't seem to be working correctly. Even though I tried the following code, I can't figure out why it's not functioning as expected. Is there a diff ...

The CSS media query isn't functioning properly on Safari browser

Currently, I am working on a project using React JS and CSS. In order to make it responsive, I have implemented media queries. However, I have encountered an issue where the media query is not functioning properly in Safari browsers on both phones and PC ...

Tslint is notifying that JSX elements without any children must be self-closing to prevent errors [Error]

Recently, I encountered an issue while trying to build my solution using the command npm run build. The error message displayed was: JSX elements with no children must be self-closing. I came across a similar problem on Stack Overflow but unfortunately ...

Error: It seems that the function (0 , _redux_slices_loginAuthApiSlice__WEBPACK_IMPORTED_MODULE_4__.useLoginMutation) is not a valid function or the value it returns is not iterable

Need help with resolving an issue in NextJS 14. Please guide me if I am doing anything wrong. Here are the package versions: "@reduxjs/toolkit" : "^2.0.1", "next" : "^14.0.4", "react" : "^18", "react-dom" : "^18", "react-redux" : " ...

Personalizing the hamburger icon in Bootstrap 4.0

I want to modify the color of the three lines as well as the border around the icon using CSS, but I'm unsure which tags to target. CSS: .navbar-toggler .navbar-toggler-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox=& ...