What is the best way to position a Radio group next to a TextField in Material UI

I've been through the documentation, but I'm struggling to understand how styling works in Material UI.

Currently, I have a radio-group component set up like this:

import React from 'react'
import Radio from '@material-ui/core/Radio'
import RadioGroup from '@material-ui/core/RadioGroup'
import FormControlLabel from '@material-ui/core/FormControlLabel'
import FormControl from '@material-ui/core/FormControl'
import FormLabel from '@material-ui/core/FormLabel'

import { makeStyles } from '@material-ui/core/styles'

const useStyles = makeStyles((theme) => ({
    root: {
        '& .MuiFormLabel-root': {
            color: 'red',
        },
    },

    formControl: {
        margin: theme.spacing(3),
    },
}))

const RadioInput = (props) => {
    const classes = useStyles()
    const { label, value, setValue, name, inputs } = props

    return (
        <FormControl component="fieldset" className={classes.root}>
            <FormLabel component="legend">{label}</FormLabel>
            <RadioGroup
                aria-label={name}
                name={name}
                value={value}
                onChange={(e) => setValue(e.target.value)}
                row
            >
                {inputs.map((x, index) => {
                    return (
                        <FormControlLabel
                            key={index}
                            value={x.toLowerCase()}
                            control={<Radio />}
                            label={x}
                        />
                    )
                })}
            </RadioGroup>
        </FormControl>
    )
}

export default RadioInput

Additionally, I have a text field component structured as follows:

import React from 'react'

import { TextField } from '@material-ui/core'

import { makeStyles } from '@material-ui/core/styles'

const useStyles = makeStyles((theme) => ({
    root: {
        '& .MuiTextField-root': {
            margin: theme.spacing(1),
            width: 300,
        },
    },
}))

const TextInput = (props) => {
    const classes = useStyles()
    const { label, value, setValue, error, type, helperText } = props

    return (
        <div className={classes.root}>
            <TextField
                label={label}
                error={!!error ? true : false}
                value={value}
                onChange={(e) => setValue(e.target.value)}
                helperText={!!error ? error : helperText}
                type={type}
            />
        </div>
    )
}

export default TextInput

The problem arises when these components are combined, resulting in an unappealing layout:

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

As shown in the image, the radio button is slightly offset to the right of the text field above it. My goal is to align the labels and position the radio buttons to the left in line with the labels.

If anyone could provide some guidance on resolving this issue, I would greatly appreciate it. Despite my efforts to follow the documentation, I haven't made any progress so far.

Answer №1

Within your sandbox environment, the RadioInput.jsx file contained the following code:

import React from "react";
import Radio from "@material-ui/core/Radio";
import RadioGroup from "@material-ui/core/RadioGroup";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import FormControl from "@material-ui/core/FormControl";
import FormLabel from "@material-ui/core/FormLabel";

import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles((theme) => ({
  root: {
    color: "red",
    margin: theme.spacing(1)
  }
}));

const RadioInput = (props) => {
  const classes = useStyles();
  const { label, value, setValue, name, inputs } = props;

  return (
    <FormControl component="fieldset" className={classes.root}>
      <FormLabel component="legend">{label}</FormLabel>
      <RadioGroup
        className={classes.root}
        aria-label={name}
        name={name}
        value={value}
        onChange={(e) => setValue(e.target.value)}
        row
      >
        {inputs.map((x, index) => {
          return (
            <FormControlLabel
              key={index}
              value={x.toLowerCase()}
              control={<Radio />}
              label={x}
            />
          );
        })}
      </RadioGroup>
    </FormControl>
  );
};

export default RadioInput;

The indentation of the radio group extends further than the text field and its label due to specifying className={classes.root} (which includes an 8px margin) on both the FormControl and the RadioGroup. This causes the RadioGroup to be indented by 8px more than the other contents within the FormControl. By removing className={classes.root} from the RadioGroup, the alignment is corrected:

import React from "react";
import Radio from "@material-ui/core/Radio";
import RadioGroup from "@material-ui/core/RadioGroup";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import FormControl from "@material-ui/core/FormControl";
import FormLabel from "@material-ui/core/FormLabel";

import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles((theme) => ({
  root: {
    color: "red",
    margin: theme.spacing(1)
  }
}));

const RadioInput = (props) => {
  const classes = useStyles();
  const { label, value, setValue, name, inputs } = props;

  return (
    <FormControl component="fieldset" className={classes.root}>
      <FormLabel component="legend">{label}</FormLabel>
      <RadioGroup
        aria-label={name}
        name={name}
        value={value}
        onChange={(e) => setValue(e.target.value)}
        row
      >
        {inputs.map((x, index) => {
          return (
            <FormControlLabel
              key={index}
              value={x.toLowerCase()}
              control={<Radio />}
              label={x}
            />
          );
        })}
      </RadioGroup>
    </FormControl>
  );
};

export default RadioInput;

https://codesandbox.io/s/radiogroup-and-textfield-alignment-gmcsq?fontsize=14&hidenavigation=1&theme=dark

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

When two functions are provided, the onClick event in React / Material UI does not function as expected

Within a React Component, I am utilizing a Material UI Button. The button is expected to trigger both handlePopupClickOpen() and props.function?.(). interface ConfirmBorrowPopupProps{ amount : number; function: Function; } export function Confir ...

The server encountered an error: TypeError - It is not possible to convert undefined or null into an

Check out this Code import { getProviders, signIn as SignIntoProvider } from "next-auth/react" function handleSignIn({ providers }) { return ( <> {Object.values(providers).map((provider) => ( < ...

Issue in Firefox: Footer is wrapping around the main content

Hey, I've been dealing with a pesky bug that just won't go away. We're currently working on a redesign for www.petpoint.com - The footer looks perfectly fine in every browser except for Firefox. It gets all jumbled up for some reason. I&a ...

Optimal scenarios for implementing computed/observables in mobx

I understand most of mobx, but I have a question regarding my store setup. In my store, I have an array of objects as observables using TypeScript: class ClientStore { constructor() { this.loadClients(); } @observable private _clients ...

Chrome and Firefox browsers are not supporting HTML simple anchor links

Creating a portfolio page at this link (http://198.96.94.51/v2/) and encountering an issue with the navigationMenu. When rapidly clicking on the links on the side, they do not redirect to the correct anchor point (some don't move the page at all). I h ...

I'm curious about the distinction between React's one-way data binding and Angular's two-way data binding. Can someone please clarify the key differences

My understanding of these concepts is a bit hazy. If I were to develop the same ToDo application using AngularJS and ReactJS, what exactly distinguishes React ToDo's use of one-way data binding from AngularJS's two-way data binding? From what I ...

How can I implement a button with a linear progress bar inside using material-ui components?

I am looking to add a button with a linear progress bar similar to this demo, but using Material components instead: I have successfully integrated <CircularProgress/> into a button. However, I am having trouble incorporating <LinearProgress/> ...

Display of certain special characters such as ">" may be affected when using UTF-8 encoding

Here are the codes I'm working with: ul.pathnav a:before{ content:"\0X3E"; text-decoration:none; } I have been trying to use the hex code \0x3e for ">", but it doesn't seem to be working. However, when I tried using ...

Ensure that the child div remains at the bottom of the parent div

I'm trying to make sure that the subfooter div stays at the bottom of the childbox div like a footer. You can see the code on this jsfiddle link <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title ...

The reducer test did not return a value for GET_SUCCESS and instead returned

it(`should properly handle ${GET_POSTAL_SUCCESS}`, () => { const payload = { postalCode: { postalInfo: { postalCode: '5282', }, }, }; expect(reducer(state, { type: GET_POSTAL_S ...

What is the method for advancing the cursor to the next line in this animation?

I've created an animation that types out: "[Your Name] blah blah" with a typing effect. Now, I want the cursor to move to the next line and type out: "[Your Father Name] blah blah" I attempted to add <br>, but it types out both lines simulta ...

Able to successfully access user account on Postman, however encountering login issues when trying to do

If I can successfully log in a user using Postman, does that indicate there is a bug in my front end code? Encountered CastError: Casting to string failed with value "{ email: '[email protected]', password: '123456' }" (type Objec ...

Leveraging JSON Data for Avatars in React.js

Struggling to arrange 10 Avatars side by side for showcasing the user list. However, encountering an issue where the Avatars are being duplicated and showing incorrect initials when passing JSON data. Experimented with this in Code Sandbox linked below. h ...

Does anyone know if it's achievable to include a background position within the img /asp:image tag?

Currently, I am endeavoring to enhance the loading speed of my webpage. The initial approach I decided to pursue is base64 conversion. On my homepage, there are a total of 18 small images that need to be loaded. Since base64 encoding increases image size ...

This code snippet, document.location.search.replace('?redirect=', '').replace('%2F', ''), is failing to execute properly in Firefox

The functionality of document location search replace redirect to another page works in Chrome, however, document.location.search.replace('?redirect=', '').replace('%2F', ''); it does not work in Firefox; instead, ...

Hover and hover-off functions in navigation menu

html <div class="hidden-nav"> <h4>lorem</h4> <ul class="decor-menu-list"> <li><a href="#">123</a></li> <li><a href="#">123</a></li> <li><a hre ...

Bootstrap - placement of label to the left of the checkbox

Here is an example of a checkbox I am working with: <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="defaultCheck1"> <label class="form-check-label" for="defaultCheck1"> Default checkbox < ...

Optimal Placement of jQuery Event Handlers in React/Redux Components with Asynchronous Data Loading

After reviewing the ReactJS documentation, it's clear that the most suitable lifecycle method for handling redux action calls is componentDidMount. However, I'm facing a challenge when it comes to incorporating jQuery operations within this parti ...

Optimal approach for managing numerous modals containing map data in Next.js

Hey there, I'm facing an issue while trying to utilize map data in conjunction with modals. Although I have set the state for all modals, when I use an array object within the map data, the modals end up showing duplicated. To provide clarity, let me ...

Adding CSS classes through the .addClass method - A guide on utilizing linked CSS files

I came across this code snippet and I have a quick question. $(window).scroll(function() { var y_scroll_pos = window.pageYOffset; var scroll_pos_test = 150; // adjust as needed if(y_scroll_pos > scroll_pos_test) { $( "#cssmenu" ).addCl ...