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

Divs with floating left have a complete vertical border on their right side

I would like the first and second divs to have a full height border on their right side while floating left. CSS: div.wrapper { border: 1px solid black; } div.wrapper > div { text-align: center; width: 50px; padding-left: 5px; fl ...

Creating a unique bullet style using CSS

I've got a collection of student links that take users to their profiles, and I want to replace the usual circular bullet points with smiley faces. Each picture is 14x14 pixels in size. How can I use CSS to achieve this effect for the bullets? ul { ...

Adjust the dimensions of the initial cell

I need to adjust the size of the initial "generated" cell in a grid. The grid is not present in the HTML markup until JavaScript prints RSS information on it, making it difficult to target specific rows or cells directly. Note: The first element is hidden ...

The collapsing z-index menu in Bootstrap 4 is experiencing CSS issues and is not functioning correctly

I have a bootstrap 4 menu with a slide effect that is functioning correctly, but there seems to be an issue with the z-index value I have set for it. Specifically, there is some content within a parallax jumbotron that is overlapping the menu links. I need ...

MUI enables the creation of a fixed vertical box anchored at the bottom of the screen

I’ve attempted the following so far: import "./styles.css"; import { Box, Typography } from "@mui/material"; import styled from "@emotion/styled"; export default function App() { const MainStyle = styled("div")(( ...

Retrieve the border color using Selenium WebDriver

Hey everyone, I'm currently trying to retrieve the border color of an extjs 4.2 form control text field using the getCssValue method. However, I'm having trouble getting the value as it's coming back blank. Below is a sample of my code that ...

Seeking assistance with installing Node version >14 on Windows 8. Any guidance would be greatly appreciated

Currently running node version 13.14.0, but in order to utilize the latest create-react-app version v5.0.0, I must upgrade to node version 14 or higher. Unfortunately, this is not supported on Windows 8. Any suggestions for a workaround? Encountering an e ...

Black-colored backdrop for Mui modal

Currently working with a mui modal and encountering an issue where the backdrop appears as solid black, despite setting it to be transparent. I attempted to adjust the color to transparent, but the issue persists. ...

Guide on using jQuery to replace the applied css of an aspx control

My dilemma revolves around an AspxFileManager. I am attempting to distinguish a file when it is loaded by adding a class that places a border around the element. My initial attempt using .attr('style', 'border: 10px!important'); was uns ...

Testing useEffect with multiple api calls inside using jest and enzyme: A comprehensive guide

Looking to perform testing on useEffect with dual api calls. Any insights on how to simulate api call or spy on fetchCountry and fetchStates functions, followed by testing setCountry and setStates functions? Exploring Jest & Enzyme for this scenario. ...

Ways to stop the location object from resetting in ReactJS when reloading the page

Currently, I am using Link to redirect and call another component. The code looks something like this: <Link to={{ pathname: "/app/" + app.appId, appDetail: { app: app } }}>> When I call the path /app/:appId, it triggers the AppDetails ...

designing alternating rows within a table

Can I apply styles to alternating rows in an HTML table using only element hierarchy selectors and avoiding style names? I am tasked with styling the HTML output generated by a server component, which does not include styles for alternate rows. While I co ...

Utilizing CSS files to incorporate loading icons in a component by dynamically updating based on passed props

Is it possible to store icons in CSS files and dynamically load them based on props passed into a component? In the provided example found at this CodeSandbox Link, SVG icons are loaded from the library named '@progress/kendo-svg-icons'. Instea ...

Utilizing media queries and page width in a Moodle theme designed with Bootstrap framework

I currently have my LMS set up with Moodle 4 and the boost theme which is based on bootstrap (github) However, the default page layout appears very narrow on all devices and I would like to utilize the responsive design features of Bootstrap for different ...

navigation bar: retain link hover state even after displaying sub-menu

My navigation bar has submenus with background images in .png format. Only 3 links in my navbar have these submenus. The issue I am facing is that when the menu link is in a hover state and the submenu is being hovered over, the nav link loses its hover st ...

Challenge with the dependencies among peers

I recently integrated @material-ui/pickers into my React project and received warnings about installing peer dependencies. I followed the instructions to install them, but there is still one persistent warning. Even though I installed the dependency, I con ...

The background image in the hovering textbox shifts and changes size

I've been trying to set a background image on a Kendo UI Textbox. It looks good until you hover over it. But when you do hover over it, this issue arises: How can I resolve this? The background image should remain in place even when I hover and cli ...

How to target and style multiple descendants of an element using CSS

Can you target multiple elements with a common ancestor in CSS using class, id, etc? For example: table.exams caption, tbody, tfoot, thead, tr, th, td If not, is there a method to select all nested elements within that particular element? ...

"Creating dynamic web apps with the powerful duo of Meteor and Zurb

Just starting out with programming and currently working on a new web application using Meteor and AngularJS. I would like to incorporate the elements/css from 'Zurb Foundation For Apps' into my project... I am familiar with including Bootstrap ...

Are you ready to create a Modal Factory?

For a while now, I have been utilizing modals in various front-end frameworks to communicate with users in my applications. Typically, the process involves defining the modal's html and then rendering it through a click event. As my apps continue to ...