eduardoborges / use-mask-input

✏️ A react Hook for build elegant input masks. Compatible with React Hook Form
https://npmjs.com/package/use-mask-input
332 stars 19 forks source link

Using controlled component causes strange behavior #62

Open sergeyzwezdin opened 1 year ago

sergeyzwezdin commented 1 year ago

After connecting use-mask-input, using controlled input (passing value/onChange controlled outside), the caret puts on the first character.

Tried to use useMemo to avoid re-rendering of Input component and set its state via ref, but nothing changed.

Here is how it behaves: 2023-10-17 at 11 12 38

Repro project could be found here - https://stackblitz.com/edit/stackblitz-starters-hak8pb?file=app%2Finput.tsx

I think it could be considered as a bug.

eduardoborges commented 1 year ago

Hey @sergeyzwezdin, yes its a bug... im working on a solution. Thanks for reporting.

eduardoborges commented 1 year ago

@sergeyzwezdin I detected when using controlled component the mask alias not works as espected.

For now, you can pass full mask declaration:

const ref = useInputMask({
  mask: '9{1,}[.9{2}]',
  options: {
    placeholder: '',
    rightAlign: true,
  },
});

This example represents a decimal with optional numbers after radix point.

RHarryH commented 1 year ago

@sergeyzwezdin, @eduardoborges My workaround for that issue is to add onChange event with below content:

const caret = event.target.selectionStart;
const element = event.target;
 window.requestAnimationFrame(() => {
    element.selectionStart = caret;
    element.selectionEnd = caret;
})