How to preselect an item in a RadioGroup

We are facing a challenge in setting a default value automatically for a RadioGroup upon page load. Despite the documentation mentioning a defaultValue property (https://material-ui.com/api/radio-group/), it does not seem to work as expected.

We experimented with this issue in the provided Sandbox demo but were unsuccessful in achieving the desired outcome: https://codesandbox.io/s/material-demo-8xgmd

The code snippet used from the Sandbox demo:

  <FormControl component="fieldset" className={classes.formControl}>
    <FormLabel component="legend">Gender</FormLabel>
    <RadioGroup
      aria-label="Gender"
      name="gender1"
      className={classes.group}
      value={value}
      onChange={handleChange}
      defaultValue="male">
      <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>

Despite our attempts, we could not get the "male" radio button to be pre-selected upon page load. Are there any other properties that can be utilized for setting a default value?

FOLLOW UP QUESTION: Given that we are using React 16.2, is there a workaround to set the default value within that version of React?

Answer №1

For React Versions Supporting Hooks (> 16.8) (see stackblitz provided in the question)

To update the internal state of a React (Material Design) component, you must utilize the useState() method. By creating a state property named value and setting it to male, you inform the MD RadioGroup component about which radio button should be the default selection. Subsequently, the value property is employed as the value attribute within the radio group to establish the default choice.

A small modification is required on line 24 of the referenced sandbox:

Replace:

const [value, setValue] = React.useState("female");

With:

const [value, setValue] = React.useState("male");

For React Versions without Hooks (< 16.8)

If your project doesn't support hooks, you'll need to transform your function into a React Component Class that utilizes a standard state variable approach. However, an additional concern arises when using Material Design since it calls a React method not present in earlier versions of React (createContext()). It's recommended to downgrade Material Design to v1.0.0 if you're working with React versions prior to 16.8.

Here is the relevant code snippet:

class RadioButtonsGroup extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.classes = {
      root: { display: "flex" },
      formControl: { margin: 13 },
      group: { margin: 10 },
    };
    this.state = { value: "male" };
  }
  handleChange(event) {
    this.setState({ value: event.target.value });
  }
  render() {
    return (
      <div className={this.classes.root}>
        <FormControl component="fieldset" className={this.classes.formControl}>
          <FormLabel component="legend">Gender</FormLabel>
          <RadioGroup
            aria-label="Gender"
            name="gender1"
            className={this.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" className={this.classes.formControl}>
          <FormLabel component="legend">Gender</FormLabel>
          <RadioGroup
            aria-label="gender"
            name="gender2"
            className={this.classes.group}
            value={this.state.value}
            onChange={this.handleChange}
          >
            <FormControlLabel
              value="female"
              control={<Radio color="primary" />}
              label="Female"
              labelPlacement="start"
            />
            <FormControlLabel
              value="male"
              control={<Radio color="primary" />}
              label="Male"
              labelPlacement="start"
            />
            <FormControlLabel
              value="other"
              control={<Radio color="primary" />}
              label="Other"
              labelPlacement="start"
            />
            <FormControlLabel
              value="disabled"
              disabled
              control={<Radio />}
              label="(Disabled option)"
              labelPlacement="start"
            />
          </RadioGroup>
          <FormHelperText>labelPlacement start</FormHelperText>
        </FormControl>
      </div>
    );
  }
}

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

Inserting an item into ng-model within a dropdown menu

I have a select box populated with data from my backend. This data is an array of objects: [Object { superkund_id="4", nod_id="12068", namn="Växjö Fagrabäck"}, Object { superkund_id="5", nod_id="9548", namn="Halmstad Bågen / Pilen"}] I am using ng-o ...

The Bootstrap modal form fails to properly handle the POST method when sending data to the server

I am encountering an issue with a button that triggers a modal form <a href="#" class="btn btn-primary" data-toggle="modal" data-target="#agregarProducto">Add Material</a> The modal appears as shown below: https://i.stack.imgur.com/J39x9.pn ...

Leveraging Vue Data for Storing CSS Properties

I am currently utilizing the Quasar framework in conjunction with Vue for my application development. Below is a snippet of my code: <q-tooltip content-class="bg-amber text-black shadow-4" :offset="[10, 10]"> Save </q-tooltip> <q-tooltip c ...

Implementing data updates in Ruby on Rails through AJAX or jQuery

Within a text field input lies the value of a database attribute (ref). Upon focusing on the field, a border appears and disappears upon clicking out. My dilemma is that I wish for the data within the text field to be saved in the database without the nee ...

Discovering the parameters at your disposal within a callback function can be easily achieved in JavaScript and MongoDB

Being new to JavaScript and web development, I've been self-studying but have encountered many roadblocks. Currently, I'm struggling with understanding functions with callback functions and their parameters. The documentation I've read so f ...

Changing p tags to br tags on tinyMCE

I need assistance with using tinyMCE as an inline editor. I want it so that when a user is in edit mode and presses enter, <br /> is inserted instead of <p>. I have gone through the manual and FAQ but have not been able to achieve this successf ...

How to retrieve the context of a .js file using jQuery $.ajax without automatically executing upon receipt

Upon fetching a *.js file using $.ajax, the scripts are executed upon receipt! Is there a way to fetch and execute it only when desired? Moreover, is there a method to remove these scripts at will? ...

How to properly format JSON responses in Node.js or Express

I came across a question on Proper way to return JSON using node or Express and copied it for reference. I am looking for the response in a specific format. This is the sample format for the response API: { "success":true, "code":200, "message":"Ok", "da ...

Implementing jquery-confirm in CodeIgniter: A Step-by-Step Guide

I'm having some trouble with the jquery-confirm plugin from . Everything seems to be working fine, but when I try to delete an item, the jquery pops up an alert. However, when I click "okay", it doesn't actually delete the item. I can't figu ...

Is it mandatory to employ the spread operator in the process of updating an object while using the useState hook?

Recently delving into hooks, I stumbled upon an insightful passage in the official documentation regarding Using Multiple State Variables: It is noteworthy that updating a state variable in hooks replaces it entirely, as opposed to merging it like in th ...

Why won't the function activate on the initial click within the jQuery tabs?

When creating a UI with tabs, each tab contains a separate form. I have noticed that when I click on the tabs, all form save functions are called. However, if I fill out the first tab form and then click on the second tab, refresh the page, and go back t ...

Setting up user roles using Firebase Auth in NextJS application

Seeking a solution to implement a multi-level role system for my blog website. Currently utilizing Firebase Auth for authentication with email/password, but all users have the same posting/editing access. Looking to differentiate between Admins, Moderators ...

When the page is resized for mobile, the Bootstrap modal shifts downwards

I am encountering an issue with a modal that pops up on my webpage when clicked. It is perfectly centered in a browser view and smaller views. However, when I resize the page for phones, the modal shifts down the page and requires scrolling to see it. How ...

Issues with JSON data not functioning properly when using file system in JavaScript

When attempting to parse a JSON file, I encountered some errors. The file is located in a directory within my JavaScript file, under the 'fs' in a folder named "recipes." Within this folder, there are 3 JSON files, each representing a separate ob ...

What is causing the data added to an array to vanish after the forEach loop within the useEffect hooks?

Below is the code snippet: const Tabs = ({data, scrollX}) => { const [measures, setMeasures] = useState([]); const containerRef = useRef({}); let measureMentArray = []; useEffect(() => { data && data.forEach(item => { ...

Prop validation error: The property "title" must be a string with a value of **, but a number with a value of ** was provided

My Vue js code displays data from a JSON API in a modal. The issue is that the title should be dynamic, but it only works when clicked twice. On the first click, I get an error and the cancel button, which triggers the hidemodal() function, crashes. Can an ...

What is the best way to conceal a menu that automatically scrolls to the content when it is clicked?

Below is a Codepen with a menu that isn't behaving as expected. var menu = document.querySelector('.nav__list'); var burger = document.querySelector('.burger'); var doc = $(document); var l = $('.scrolly'); var panel = $ ...

Unable to alter the vertex color in three.js PointCloud

I'm currently facing an issue with changing the color of a vertex on a mouse click using three.js and Angular. After doing some research, I believe that setting up vertex colors is the way to go. My approach involves setting up vertex colors and then ...

JQuery form plugin experiencing issues with Ajax functionality

I am facing an issue with implementing the Jquery form plugin using ajax to insert my form data into the database. Although the validation is working correctly, the ajax call is not receiving any data in response. It seems like I might not be following the ...

What can be done to stop the caching of the route that router.push() redirects to in Next.js middleware?

Encountering an issue with client-side navigation and middleware in the router. It seems that the router is storing the initial redirect path and subsequent navigations bypass the middleware. This behavior ceases upon browser refresh and does not occur in ...