Search code examples
javascriptreactjsnumber-formattingformik

How to use React NumberFormat package in conjunction with Formik?


I have a Formik Field that I want to use alongside the React NumberFormat npm package. This is my FormGroup within Formik:

//...Other code
                <Formik
                    initialValues={this.state.diamondPurchaseGstDetails}
                    enableReinitialize={true}
                    onSubmit={this.formSubmit}
                >
                    {({ values, setFieldValue }) => (
                        <Form>
                                    <FormGroup>
                                        <Field
                                            className="form-control"
                                            name="CreditDays"
                                            type="text"
                                            component={ParseNumber}
                                        ></Field>
                                        <Label>Credit Days</Label>
                                    </FormGroup>
                        </Form>
//...Other code

The component I am passing is my custom component ParseNumber which uses the NumberFormat package. Here's the code:

import React from 'react';
import NumberFormat from 'react-number-format';

function ParseNumber() {
    return (
        <NumberFormat decimalScale={0} allowNegative={false}/>
    )
}

export default ParseNumber;

Now, my question is how do I bind the input Field value to the values prop? I tried something like value={values.CreditDays} but it didn't seem to work.

Edit: Here's the working codesandbox link: codesandbox


Solution

  • the Field component, and the useField hook both supply useful props and values respectively. Namely an object called field, which holds name ,value, onChange, and onBlur. These can just be spread over whichever component you're trying to bind to formik

    Using hooks (useField) is my prefered method

    import { useField } from 'formik'
    
    function NumberFieldHooks(props) {
      const { name } = props
      const [field] = useField(name)
      
      return <NumberFormat {...field} decimalScale={0} allowNegative={false}/>
    }
    
    function NumberField({ field }) {
      return <NumberFormat {...field} decimalScale={0} allowNegative={false} />;
    }
    
    // later in the formik component
    return (
      <Formik {...props}>
        <Form>
          {/* using the hooks form */}
          <NumberFieldHooks name="CreditDaysHooks" />
    
          {/* using the component prop */}
          <Field name="CreditDays" component={NumberField} />
        </Form>
      </Formik>
    )