2
votes

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

<Field
          component={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-components/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

3

3 Answers

3
votes

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

2
votes

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

  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 component 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>
  );
};
0
votes

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