Home > database >  React Multistep Form with Material UI
React Multistep Form with Material UI

Time:08-20

I do got a working Multi Step React form structured like this:

MultiStep1.js
MultiStep2.js
MultiStep3.js
MultiStepForm.js
MultiStepSubmit.js

See this Codesandbox for more!

In addition I want to add Material ui components for a better design. At this point I am not able to pass/update props (data.age) to the Material ui Component.

  <FormControl sx={{ m: 1, width: 130 }}>
    <InputLabel id="demo-simple-select-label">Age</InputLabel>
    <Select
      labelId="demo-simple-select-label"
      id="demo-simple-select"
      value={data.age}
      label="Age"
      onChange={handleChange}
    >
      <MenuItem value={10}>Ten</MenuItem>
      <MenuItem value={20}>Twenty</MenuItem>
      <MenuItem value={30}>Thirty</MenuItem>
    </Select>
  </FormControl>

The selected menu item is in fact caught, even if it is not visible (why?) but is added to the formData as undefined instead of updating the age value. How can I make the Material ui Component update the age value?

And why is the MenuItems NOT visible when selected?

CodePudding user response:

How about this instead?:

const Step1 = (props) => {
  const [age, setAge] = React.useState("");

  const { data, handleChange, next } = props;
  console.log(data);

  const selectionChangeHandler = (event) => {
    console.log(event.target.value);
    setAge(event.target.value);
    data.age = event.target.value; 
    handleChange(event);
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      <FormControl sx={{ m: 1, width: 130 }}>
        <InputLabel id="demo-simple-select-label">Age</InputLabel>
        <Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={age}
          label="Age"
          onChange={selectionChangeHandler}
        >
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>

      <FormControl sx={{ m: 1, width: 130 }}>
        <Button variant="contained" onClick={next}>
          Continue
        </Button>
      </FormControl>
    </Box>
  );
};
export default Step1;

You're using the <Select> as a controlled component, so I used your state value, and update the data object using that value instead. If you bind the Select control to data.age, then that dropdown value won't change when you change the dropdown, it will instead change when you change the value of data.age.

  • Related