Achieving left alignment for Material-UI Radio buttons: Float them left

Click here to view the demo

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

Check out the demo above to see the code in action. I'm currently struggling to align the radio buttons horizontally, wondering if there's an easier way to achieve this using Material-UI.

Is there a simple solution within Material-UI for horizontal alignment of radio buttons? Or should I just go ahead and style my own buttons, which would probably take me only 5 minutes?

import React from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import Radio from "@material-ui/core/Radio";
import RadioGroup from "@material-ui/core/RadioGroup";
import FormHelperText from "@material-ui/core/FormHelperText";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import FormControl from "@material-ui/core/FormControl";
import FormLabel from "@material-ui/core/FormLabel";

const styles = theme => ({
  root: {
    display: "flex"
  },
  formControl: {
    float: "left",
    margin: theme.spacing.unit * 3
  },
  group: {
    margin: `${theme.spacing.unit}px 0`
  }
});

class RadioButtonsGroup extends React.Component {
  state = {
    value: "female"
  };

  handleChange = event => {
    this.setState({ value: event.target.value });
  };

  render() {
    const { classes } = this.props;

    return (
      <div className={classes.root}>
        <FormControl
          component="fieldset"
          required
          className={classes.formControl}
        >
          <FormLabel component="legend">Gender</FormLabel>
          <RadioGroup
            aria-label="gender"
            name="gender1"
            className={classes.group}
            value={this.state.value}
            onChange={this.handleChange}
          >
            <FormControlLabel
              value="female"
              control={<Radio />}
              label="Female"
            />
            <FormControlLabel value="male" control={<Radio />} label="Male" />
            <FormControlLabel value="other" control={<Radio />} label="Other" />
            <FormControlLabel
              value="disabled"
              disabled
              control={<Radio />}
              label="(Disabled option)"
            />
          </RadioGroup>
        </FormControl>
        <FormControl
          component="fieldset"
          required
          error
          className={classes.formControl}
        >
          <FormLabel component="legend">Gender</FormLabel>
          <RadioGroup
            aria-label="gender"
            name="gender2"
            className={classes.group}
            value={this.state.value}
            onChange={this.handleChange}
          >
            <FormControlLabel
              value="male"
              control={<Radio color="primary" />}
              label="Male"
            />
            <FormControlLabel
              value="female"
              control={<Radio color="primary" />}
              label="Female"
            />
            <FormControlLabel
              value="other"
              control={<Radio color="primary" />}
              label="Other"
            />
            <FormControlLabel
              value="disabled"
              disabled
              control={<Radio />}
              label="(Disabled option)"
            />
          </RadioGroup>
          <FormHelperText>You can display an error</FormHelperText>
        </FormControl>
      </div>
    );
  }
}

RadioButtonsGroup.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(RadioButtonsGroup);

Answer №1

Visit this link to view a demonstration

The radio buttons within the RadioGroup elements can be displayed in a row by utilizing flexbox styling.

To achieve this, simply add the following line to the group style:

flexDirection: 'row',

This approach leverages Material-UI's pre-existing use of flexbox styling for the group. Using float: 'left' will not yield the desired outcome.

Alternatively, you can apply display: 'inline-block' to the group for a similar row-style display, albeit with fewer customization options.

Answer №2

There isn't a preset method for achieving this in Material UI; you'll need to tackle it independently, which can actually lead to a more tailored solution.

Answer №3

https://codesandbox.io/s/yp84vnzpq1

import React from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import Radio from "@material-ui/core/Radio";
import RadioGroup from "@material-ui/core/RadioGroup";
import FormHelperText from "@material-ui/core/FormHelperText";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import FormControl from "@material-ui/core/FormControl";
import FormLabel from "@material-ui/core/FormLabel";

const styles = theme => ({
  formControl: {
    display: "flex",
    float: "left",
    margin: theme.spacing.unit * 3
  },
  group: {
    float: "left",
    flexDirection: "row",
    margin: `${theme.spacing.unit}px 0`
  }
});

class RadioButtonSelection extends React.Component {
  state = {
    value: "option 1"
  };

  handleRadioChange = event => {
    this.setState({ value: event.target.value });
  };

  render() {
    const { classes } = this.props;

    return (
      <div className={classes.root}>
        <RadioGroup
          aria-label="options"
          name="options"
          className={classes.group}
          value={this.state.value}
          onChange={this.handleRadioChange}
        >
          <FormControlLabel value="option 1" control={<Radio />} label="Option 1" />
          <FormControlLabel value="option 2" control={<Radio />} label="Option 2" />
          <FormControlLabel value="option 3" control={<Radio />} label="Option 3" />
        </RadioGroup>

      </div>
    );
  }
}

RadioButtonSelection.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(RadioButtonSelection);

Answer №4

Experience the versatility of radio group settings in MUI v5 by switching between row and column layouts

       <RadioGroup
          row
          aria-labelledby="mstatus" defaultValue="Single" value={value}
          onChange={handleMaritalChange} name=...../>

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

Unable to reinitialize MUI DatePicker after keydown event

Encountering an unusual behavior that defies explanation has left me puzzled. You can explore the code sandbox here. I am attempting to enable resetting a readOnly field by pressing DEL or BACKSPACE, but it seems to be ineffective. Oddly enough, I can suc ...

What methods can a Discord Bot use to respond with specific messages to individual users?

Hey there! I'm dipping my toes into the world of coding and thought it would be fun to create a Discord bot that gives different responses each time it's mentioned. Just so you know, I'm working with Discord.js version 13 for this project. ...

Add data to a DataTable without the need to manually refresh the page

I am looking to dynamically append a DataTable on my webpage. The goal is to have a form that users can fill out multiple times and each time they submit their inputs, the results will be added to the DataTable for display. <table id="table" class="di ...

React: automatically close other SubMenus when a new SubMenu is opened

Is there a way to automatically close all other open SubMenus when a user opens a new SubMenu? If anyone has a solution, I would greatly appreciate the help! This is my code: Menu.tsx -> const Menu: React.FC = ({ data }) => { return ( ...

What is the best way to create a header similar to the one in the image using only CSS

Wondering if it's possible to create a header like the one in the image using just pure CSS and without Photoshop. How can I design it in a professional manner? You can view an example of the image here. ...

Eliminate the space between the navigation bar and carousel when using Materialize with Vue.js and Laravel

I am facing an issue with the gap between the navbar and carousel in my materialize design. I have implemented Vue components for each div and Laravel as the backend. Using Sass for CSS preprocessing, I attempted to adjust the margins for the body, navbar, ...

Filling out a form within a webpage fetched through a DOMParser

Creating automation software in JavaScript using TamperMonkey. The script performs several AJAX requests that retrieve HTML to be parsed with a DOMParser. Is there a way to submit these forms without opening the newly retrieved HTML on the main page? ...

The functionality of Ng-Show is acting up

$scope.stay = function() { alert("Inside Keep me In") $scope.timed = false; $scope.isLogStatus = true; } $scope.displayAlert = function() { $scope.timed = true; alert("inside display") } function idleTimer() { var t; $window.o ...

Discovering the correct element and typing for an HTML attribute through JavaScript

We are currently working on test automation and I am looking for a way to identify the Element and Type associated with it within an html (Data-qa) attribute. For example, when looping through, the Element is identified as input and the type is radio. < ...

Exploring how to incorporate Express middleware into Firebase Functions for handling HTTPS requests

Encountering a challenge while using Express middleware with Firebase Functions. In this sample, a function is linked to the app() instance as shown below: app.get('*', (req, res) => { res.send(`Hello ${req.user.name}`); }); exports.autho ...

A comprehensive guide on organizing JavaScript files within an Angular project

In the process of building my MEAN app, I have structured my folders in the following way: I have included a js file in /angular/src/assets/js for jQuery functionalities. To achieve this, I utilized npm to install jQuery. Now, I am faced with the task o ...

Node(Meteor) experiencing a memory leak due to setTimeout

I have encountered an unusual memory leak associated with the use of setTimeout. Every 15 seconds, I execute the following code using an async function that returns an array of promises (Promise.all). The code is supposed to run again 15 seconds after all ...

Javascript textfield button function malfunctioning

Here is the code I have created: HTML: <form method="post" id="myemailform" name="myemailform" action="form-to-email.php"> <div id="form_container"> <label class="descriptio ...

Ways to retrieve form information from a POST request

I received a POST request from my payment gateway with the following form data: Upon trying to fetch the data using the code snippet below, I encountered errors and gibberish content: this.http .post<any>('https://xyz.app/test', { ti ...

Tips for containing `overflow` within a flexbox container

I've organized my body space into three sections: header, content, and footer. To achieve a sticky footer effect at the bottom, I used the flex property in my layout. However, I'm struggling to add a scrollbar to my main container box. I've ...

Having trouble getting a jQuery variable to work as an argument in an onclick function for an HTML

success: function(jsonresponse) { data = JSON.stringify(jsonresponse); $.each(JSON.parse(data), function (index, item) { var Id=item.id; var JobId=item.JobId; var eachrow = "<tr>" + "<td>" + item.id + "</td>" ...

Having trouble getting CSS Image Hover to work correctly?

I'm having trouble implementing a hover effect that changes the color of an image to blue when it is hovered over by the mouse. I've defined a class for the images and styled it in my CSS, but the effect isn't working as intended. I've ...

Troubleshooting Vue v-for loop triggering click events on multiple items simultaneously

After conducting a thorough search, I haven't found a suitable answer for my issue. The problem I am facing involves a v-for loop with buttons on each item, using VueClipboard2 to copy text. Whenever a button is clicked, some CSS changes are applied t ...

404 Error: JSON POST and GET Request Not Located

I need assistance with setting up an API in Django as I am encountering errors in the JavaScript console. The error messages are: GET http://127.0.0.1:8000/edit/undefined 404 (Not Found) POST http://127.0.0.1:8000/edit/undefined 404 (Not Found) Is there a ...

reasons why the keypress event may not be triggered

Hello there, I am trying to create a function that simulates pressing the 'tab' key. The function is supposed to restrict input within specific ranges and return the cursor to another range once the limit is reached. Additionally, if a user input ...