GoncharukOrg / react-input

109 stars 9 forks source link

Initial value not set if used with react-hook-form #3

Closed SpadarShut closed 1 year ago

SpadarShut commented 1 year ago

I'm trying to use this library with react-hook-form and the initial input value doesn't get set:

Here's a codesandbox: https://codesandbox.io/s/react-input-mask-react-hook-form-bug-xig2km?file=/src/App.js

import { useForm } from "react-hook-form";
import { useMask } from "@react-input/mask";

function mergeRefs(...refs) {
  return (value) => {
    for (const ref of refs) {
      if (typeof ref === "function") {
        ref(value);
      } else if (ref != null) {
        ref.current = value;
      }
    }
  };
}

export default function App() {
  const { handleSubmit, register } = useForm({
    defaultValues: { phone: "12345678" }
  });

  const phoneField = register("phone");
  const maskRef = useMask({
    mask: "___________",
    replacement: "_"
  });

  return (
    <form onSubmit={handleSubmit(console.log)}>
      <p>This field doesn't get default value if maskRef is used</p>
      <input
        type="text"
        {...phoneField}
        ref={mergeRefs(phoneField.ref, maskRef)}
      />
    </form>
  );
}
GoncharukBro commented 1 year ago

Fixed in version 1.0.13. When using existing dependencies, you can upgrade to the latest version using the command:

npm i @react-input/mask@latest

Please provide feedback if possible.

SpadarShut commented 1 year ago

Thanks for the fix, works like a charm!