简体   繁体   中英

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>

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM