What is the easiest way to update the border color of a radio button in Material-UI?

I am looking to customize the appearance of the outer ring on Material UI radio buttons.

https://material-ui.com/components/radio-buttons/

Currently, my radio button looks like this:

https://i.stack.imgur.com/o67mN.jpg

However, I would like it to look more like this:

https://i.stack.imgur.com/24Gx0.png

I have attempted to style the PrivateRadioButtonIcon-layer class in blue and the MuiSvgIcon-root class in black, but I am struggling to find a way to style the PrivateRadioButtonIcon-layer.

Answer №1

I will outline two solutions that are relevant to MUI version 5:

  1. Using CSS only: This solution allows you to change the color of the border and circle independently.
  2. Custom icon solution: This method involves using a custom icon to customize the design as desired.

CSS-only Solution

If your goal is to solely alter the border color without affecting its thickness, particularly in MUI 5, you can achieve this through the sx prop by following these steps:

  1. To style the border, target the selector
    '& .MuiSvgIcon-root:not(.MuiSvgIcon-root ~ .MuiSvgIcon-root)'
    , utilizing the CSS general sibling combinator.
  2. To style the circle, utilize the selector
    '& .MuiSvgIcon-root + .MuiSvgIcon-root'
    , which uses the CSS adjacent sibling combinator (+) to access the second SVG element.

The complete code snippet for Radio button customization:

<Radio
    {...otherRadioProps}
    sx={{
        '& .MuiSvgIcon-root:not(.MuiSvgIcon-root ~ .MuiSvgIcon-root)': {
            color: 'red',
        },
        '& .MuiSvgIcon-root + .MuiSvgIcon-root': {
            color: 'blue',
        },
    }}
/>

Important Notes:

  1. Border Thickness: While it's not possible to make the border thinner according to your design preferences, you can increase the border thickness through CSS alone. To manipulate the path element inside the SVG for the radio button's surrounding border, include the following in the sx prop:

    '& .MuiSvgIcon-root:not(.MuiSvgIcon-root ~ .MuiSvgIcon-root) path':
        {
            stroke: 'red',
            strokeWidth: 3,
        },
    

    https://i.stack.imgur.com/95Vyi.png

    Note that despite setting the color: 'red' on the .MuiSvgIcon-root element, you still need to specify stroke: 'red',.

  2. Directly targeting the circle using a class name isn't feasible due to Material UI assigning the same class name to both the border and circle elements, as depicted in this Firefox DevTools screenshot:

    https://i.stack.imgur.com/z27JF.png

Solution with Custom icon and checkedIcon Component

If you desire a thinner border, incorporating custom SVG icons via the icon and checkedIcon props becomes necessary. To achieve the desired look shown below:

https://i.stack.imgur.com/mb33R.png

You can implement the following icon component:

const RadioButton = ({ checked }) => (
    <svg
        width="38px"
        height="38px"
        viewBox="0 0 24 24"
        fontSize="38px">
        <circle
            cx="50%"
            cy="50%"
            r="11px"
            stroke="red"
            stroke-width="1px"
            fill="none"
        />
        {checked && (
            <circle
                cx="50%"
                cy="50%"
                r="6px"
                fill="blue"
            />
        )}
    </svg>
);

Integrate the custom icon component into your MUI Radio component like so:

<Radio
    icon={<RadioButton />}
    checkedIcon={<RadioButton checked />}
    {...otherProps}
/>

Answer №2

1 - You are using the material UI tag like this:-

<FormControlLabel value="" control={<Radio />} label="" />

2 - Add a className to it and style the Radio tag as follows:-

<FormControlLabel className="targetInsideOfRadio" value="" control={<Radio style={{color: "#979797"}} />} label="" />

3 - Open the custom.css file and include the following CSS code:-

.targetInsideOfRadio > span > span > div > svg ~ svg > path {
     color: #2149b9;
 }

4 - Hopefully, this solution helps you find the answer :)

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

Execute a function that handles errors

I have a specific element that I would like to display in the event of an error while executing a graphql query (using Apollo's onError): export const ErrorContainer: React.FunctionComponent = () => { console.log('running container') ...

What is the most effective way to alter the font within this Bootstrap template?

Check out the source code on Github. I've been attempting to modify the font-family for both h1 and body elements, but it's not working as expected. I must be overlooking something simple, but I can't seem to pinpoint the issue. It's d ...

Is there a way to ensure my chat view functions properly without relying on partial views?

I am currently working on integrating a private chat feature using SignalR in my project, and I have encountered an issue while creating a View with accessible model values to pass to the server. Specifically, I have a list of doctors, and when a user clic ...

What is the best way to align the CardHeader title at the center in React Material-UI?

In my project, I am trying to get the "Edit" and "Delete" actions to be vertically aligned in the center of the CardHeader. Currently, as you can see in the screenshot, these buttons are not properly aligned with the title and avatar of the CardHeader. Whi ...

Executing function statement

I'm currently learning about React hooks, and I have a question regarding the behavior of two function expressions within different useEffect hooks. In one case, the function expression named timerId in the first useEffect is invoked automatically wit ...

Tips on making a material-ui grid fill up the entire screen

Currently, I am working on developing a layout that resembles most editor/IDE setups using material-ui and react. In this layout, I have a top bar, a bottom bar, side panels on both sides, and a center area. My main concern is how to ensure that this grid ...

The deployment of the React Single Page Application on Netlify encountered errors during the

Whenever I try to deploy the website after successfully running it locally, I encounter this error message in the log file: In between the errors Failed to compile. and npm ERR! code ELIFECYCLE, there are some warnings about using == instead of === and ha ...

Attempting to use jQuery on click to set the background image of a div to a base64 encoded data image

Check out what I'm working on here The first div contains html with data:image;base64 <div id="large_photo_null" style="width:50px; height:50px; background-image: url( data:image;base64,R0lGODlhR.. );" > </div> When using html, the ba ...

The Importance of Strict Contextual Escaping in ReactJS

When making an API call, we receive a URL in the response. In Angular JS, we can ensure the safety of this URL by using $sce.trustAsResourceUrl. Is there an equivalent function to trustAsResourceUrl in React JS? In Angular, //Assuming 'response&apos ...

Trying to display logo using 'content' property in CSS

I've been trying to display a logo on the header of my website, but I'm having trouble getting it to show up. I attempted to set the logo using HTML syntax as well as the following CSS code: .div { content: url (...jpg); } However, both metho ...

Employ the Material UI autocomplete feature in freeSolo mode by integrating it with react-hook-form

My current goal is to implement Material UI's autocomplete in free solo mode for a combo-input. This setup should allow users to either choose a suggested option through autocomplete or, if no suggestion fits, use their input as the final form value. ...

Having trouble inputting text into input field using ReactJS

I am currently facing a challenge while attempting to modify the value of an input field using ReactJS. The issue I am encountering is the inability to input values into the field. After reviewing several other queries, it appears that simply changing the ...

Hiding a Component: Achieving Smooth Behavior with Timer and onPress

My goal is to create a user interface where tapping the screen displays a <TouchableWithoutFeedback> component, which should automatically disappear after 4 seconds. Additionally, I want the user to be able to tap on the displayed component to hide ...

What is the process for spinning an image?

Is there a way to rotate an image around its center? I am looking for a solution where the image rotates continuously when clicked, but stops if an ajax call is unsuccessful. Please assist me in finding a resolution. ...

What is the best way to position my image in the center within a blank canvas?

What is the best way to center an image in a white space? I am working with HTML, PHP, and CSS, but I am unsure of how to achieve this. So far, I have tried aligning the image within text on w3schools.com, but my other attempts like: #image { margin- ...

Omit the use of "default" when importing a JSON file in Vite+React with Typescript

Each time I attempt to import a JSON file, it seems to enclose the JSON within a "default" object. When trying to access the object, an error message displays: Property 'default' does not exist on type... I have already configured resolveJsonMod ...

Fuzzy division following a CSS transformation/animation

I have been working on a content slider, using the guidelines from this demonstration However, I have encountered an issue where my content, which consists of a few divs, appears slightly blurry after the CSS transition completes. This problem only seems ...

How come I'm encountering issues when trying to click on the "register-selection" button in my Bootstrap and JS setup?

I am facing a challenge while developing my website. I want to trigger an alert when the "register-selection" is clicked, but despite trying both Jquery and vanilla Javascript, I have not been successful. Even after searching online resources and ChatGPT f ...

Setting the flex-direction for <td> elements: A helpful guide

This is a snippet from the render function of one of my components, showcasing a table: return ( ... <td> <div style={{ width: '100%' }}>50</div> {' '} <span clas ...

Customize the underline color of Material-UI's Input component

Trying to create an input component with a white underline. However, the underline color changes to black when hovering over it. It should remain white. Override the underline class as shown in the demo and instructions below. Despite trying to implement t ...