Search code examples
reactjsselectmaterial-uiformikyup

Select Material UI Tag Does not show error using Yup and formik


When nothing is selected, it should print the error, however, by inspecting elements I could see the error label but does not appear. Another problem is that the label "Country" does not appear. This happens only in the select tags in MUI and in TextField below which is the "Zip" tag it is okay.

    <Select
              labelId="demo-simple-select-label"
              required
              fullWidth
              label="Country" 
              name="country"
              id="demo-simple-select"
              value={formik.values.country}
              onChange={formik.handleChange}
              error={
                formik.touched.country && Boolean(formik.errors.country)
              }
              helperText={formik.touched.country && formik.errors.country}
            >
              <MenuItem value={"DE"}>Germany</MenuItem>
              <MenuItem value={"FR"}>France</MenuItem>
            </Select>

enter image description here


Solution

  • I managed to find an answer: Try this out:

    import { FormHelperText } from "@mui/material";
    
      <FormControl>
          <Select
            labelId="demo-simple-select-label"
            required
            fullWidth
            label="Country" 
            name="country"
            id="demo-simple-select"
            value={formik.values.country}
            onChange={formik.handleChange}
            error={
               Boolean(formik.touched.country && formik.errors.country)
            }
          >
             <MenuItem value={"DE"}>Germany</MenuItem>
             <MenuItem value={"FR"}>France</MenuItem>
          </Select>
          {formik.touched.country && formik.errors.country ? (
             <FormHelperText
                sx={{ color: "#bf3333", marginLeft: "16px !important" }}
             >
                {formik.touched.country && formik.errors.country}
             </FormHelperText>
             ) : null}
      </FormControl>
    

    Hope it helped!!