最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Formik MaterialUI input masking - Stack Overflow

programmeradmin2浏览0评论

I have a form in formik and fields generally look like that:

<Field
          ponent={TextField}
          name="phoneNumber"
          type="text"
          required
          label={t('containers:CommonFields.phoneNumber')}
          variant="outlined"
          margin="normal"
/>

Where Field is imported from Formik and TextField is just styled formik-material-ui textfield:

import { TextField } from 'formik-material-ui';
import breakpoints from 'styles/breakpoints';
import styled from 'styled-ponents/macro';

export default styled(TextField)`
  ${breakpoints.md`
    max-width: 320px;
  `};
  width: 100%;
`;

What i want to do is add input mask to that field using react-input-mask. This is what I've got so far:

Unfortunately the input is not rendering

I have a form in formik and fields generally look like that:

<Field
          ponent={TextField}
          name="phoneNumber"
          type="text"
          required
          label={t('containers:CommonFields.phoneNumber')}
          variant="outlined"
          margin="normal"
/>

Where Field is imported from Formik and TextField is just styled formik-material-ui textfield:

import { TextField } from 'formik-material-ui';
import breakpoints from 'styles/breakpoints';
import styled from 'styled-ponents/macro';

export default styled(TextField)`
  ${breakpoints.md`
    max-width: 320px;
  `};
  width: 100%;
`;

What i want to do is add input mask to that field using react-input-mask. This is what I've got so far:

https://codesandbox.io/s/priceless-currying-hryv1

Unfortunately the input is not rendering

Share Improve this question edited Sep 17, 2020 at 9:06 Ahmed Ashour 5,61110 gold badges39 silver badges62 bronze badges asked Sep 17, 2020 at 9:03 user7605119user7605119
Add a ment  | 

3 Answers 3

Reset to default 3

Change your TextField import to

import { TextField } from "@material-ui/core";

updated sample

or, if you want to keep formik textfield then check this demo

You need to change a couple of things inside your FormikTextField ponent.

  1. You don't need a local state, your input should be controlled by Formik.
  2. You need to pass the props that Formik Field sends its children into InputMask.
  3. You need to pass input props to children inside InputMask.

In the end, the working ponent should look something like

const FormikTextField = (props) => {
  return (
    <InputMask
      {...props}
      {...props.field}
      mask="(0)999 999 99 99"
      disabled={false}
      maskChar=" "
    >
      {(inputProps) => <StyledTextField {...inputProps} />}
    </InputMask>
  );
};

Please have a look at working version. I think we need to use useField hook provided by formik and use the ponent directly inside the formik form, not as ponent prop.

发布评论

评论列表(0)

  1. 暂无评论