eduardoborges / use-mask-input

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

Using controlled component causes strange behavior #62

Open sergeyzwezdin opened 11 months ago

sergeyzwezdin commented 11 months 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 11 months ago

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

eduardoborges commented 11 months 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 9 months 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;
})