s-yadav / react-number-format

React component to format numbers in an input or as a text.
MIT License
3.9k stars 410 forks source link

Why NumericFormat is not working with react-hook-form refs? #841

Closed mtsdalmolin closed 6 months ago

mtsdalmolin commented 6 months ago

Describe the issue and the actual behavior

I am trying to integrate NumericFormat with react-hook-form, but it seems not to be working properly. I need to render the input with defaultValues specified in useForm hook call, but appears that NumericField is not reflecting this behavior.

Code snippet
import { useForm, FormProvider } from 'react-hook-form';
import { NumericFormat } from 'react-number-format';

function App() {
  const methods = useForm({
    defaultValues: {
      value: 1200,
    },
  });

  const { register } = methods;

  const registered = register('value');

  return (
    <FormProvider {...methods}>
      <h1>Why it doesn't work?</h1>
      <div className="card">
        not working
        <NumericFormat {...registered} />
        <br />
        not working
        <NumericFormat {...registered} getInputRef={registered.ref} />
        <br />
        working
        <input {...registered} />
      </div>
    </FormProvider>
  );
}

export default App;

Describe the expected behavior

I need to render the default values passed in useForm hook in the input so the form comes pre-filled for the user.

Provide a CodeSandbox link illustrating the issue

https://stackblitz.com/edit/vitejs-vite-yf4qng?file=src%2FApp.tsx&terminal=dev

Provide steps to reproduce this issue

In the example provided in the link above, I am using the component NumericFormat aside with a regular input and it shows exactly what I'm trying to achieve.

Please check the browsers where the issue is seen

Zionhes commented 6 months ago

First of all I think you have to put NumericFormat inside a React-Hook-Form Controller, try this:

import { Controller, useForm, FormProvider } from "react-hook-form";
import { NumericFormat } from "react-number-format";

function App() {
  const methods = useForm({
    defaultValues: {
      value: 1200,
    },
  });

  const { control } = methods;

  return (
    <FormProvider {...methods}>
     <Controller
      name="value"
      control={control}
      render={({ field }) => (
        <NumericFormat
          {...field}
          type="text"
        />
      )}
    />
    </FormProvider>
  );
}

export default App;