DEV Community

Discussion on: React Form using Formik, Material-UI and Yup.

Collapse
 
larissamorrell profile image
Larissa Morrell

Great tutorial!

I'm trying to use a select, and I'm using the material-ui example

<TextField
   select
   id="building-select"
   name="building"
   helperText="Please select the building"
   label="Building"
   value={values.building}
   onChange={change.bind(null, 'building')}
   variant="outlined"
>
   {_.map(buildingArr, building => (
    <MenuItem key={building.uuid} value={building.value}>
      {building.name}
     </MenuItem>
   ))}
</TextField>

But when I use the change() I don't get the value. Any suggestions?

Collapse
 
finallynero profile image
Nero Adaware • Edited

I ran into this problem some time ago. Material ui select don't use the same change handlers like the input and text fields.
Formik provides us with a change handler called(handleChange) as props so you can use that.
That is what i used in the example below

const CreateUserForm = ({ classes }) => {
  const {
    values: { username, password, role },
    errors,
    touched,
    handleChange,
    isValid,
    setFieldTouched,
    handleSubmit,
    isRequesting
  } = props;
  const users = [
    { value: "admin", label: "admin" },
    { value: "cndidate", label: "candate" },
    { value: "examiner", label: "examiner" },
    { value: "examadmin", label: "examadmin" }
  ];
  const change = (name, e) => {
    e.persist();
    handleChange(e);
    setFieldTouched(name, true, false);
  };
  return (
    <form className={classes.form} onSubmit={handleSubmit}>

      <TextField
        id="role"
        select
        label="Role"
        className={classes.textField}
        value={role}
        onChange={handleChange("role")}
        SelectProps={{
          MenuProps: {
            className: classes.menu
          }
        }}
        helperText="Please select your role"
        margin="normal"
        variant="outlined"
      >
        {users.map(option => (
          <MenuItem key={option.value} value={option.value}>
            {option.label}
          </MenuItem>
        ))}
      </TextField>
      <Button
        type="submit"
        fullWidth
        variant="contained"
        color="primary"
        className={classes.submit}
        disabled={!isValid}
      >
        Create User
      </Button>
    </form>
  );
};

so your onChange should be onChange={handleChange('building')} , building being the name for that select

Collapse
 
larissamorrell profile image
Larissa Morrell

So I guess my question now is how can I customize handleChange? For simplicity, what I need to be able to do is make an axios call, sending select's value onChange.