GoncharukOrg / react-input

100 stars 7 forks source link

Using value or defaultValue not applying initial formating #32

Open bycolour2 opened 2 weeks ago

bycolour2 commented 2 weeks ago

Using hook to create only number input with visible separation on thousands

But using internal values passed as default props not being format initially

repro https://stackblitz.com/edit/vitejs-vite-ph2dm3?file=src%2FInput.tsx

GoncharukBro commented 2 weeks ago

To support the concept of controlled input, the value itself does not change outside the input process, which means that the input element will contain exactly the value you give it.

To initialize a formatted value, you must do the formatting yourself at the initialization stage, this is possible using the Intl.NumberFormat constructor used to format the value in the package itself, for example:

const inputRef = useNumberFormat( {
  locales: 'ru',
  maximumFractionDigits: 0,
});

// ...

<input
  ref={inputRef}
  defaultValue={new Intl.NumberFormat('ru',  { maximumFractionDigits: 0 }).format(value)}
/>
bycolour2 commented 2 weeks ago

Okay got it, but does defaultValue affect controling input somehow? Why dont add it to hook props?

GoncharukBro commented 1 day ago

We intentionally do not add forced change of the input element value, as it can lead to controversial situations, for example:

Let's assume that the mask field is set to "1__-___", while the value that we set in the defaultValue field is "1".

This situation is controversial, due to the fact that we cannot clearly say whether "1" from the set value is the desired first or second character in the final value, which leads to opacity of the tool and does not eliminate additional manipulations to resolve edge cases by users of the tool.

That is why we leave the choice to the user, depending on what situation his case relates to, the user can either format the value for initialization, or not format it and leave it unchanged.

bycolour2 commented 1 day ago

Okay, from the mask perspective it's understandable, but number input isn't so clear If i need to handle initial value formatting, why should i use lib after all, if i could just use my implementation? (No offence, just thought)

GoncharukBro commented 23 hours ago

Of course, what you say makes sense, we will look into applying number formatting to uncontrolled inputs in the next release. Thanks for the recommendation on how to improve the library usage.

bycolour2 commented 22 hours ago

Thank you 👍