Formatting of NumberInput and TextInput breaking after X chars pressed
See original GitHub issueWhat you were expecting: In my case, user needs to enter revenue, based on which i will filter the results. Since revenue can be a huge number, i am trying to format the number using String.toLocaleString() so that it looks good and parse the value back to number when submitted to API
For this i have created 2 functions
const numberParser = (value) => (value ? parseInt(value, 10) : 0);
const numberFormatter = (value) => {
return value?.toLocaleString();
};
and in my filters, i have defined a filter like this
<TextInput
label="Min Revenue"
source="revenue_min"
key="revenue_min"
format={numberFormatter}
parse={numberParser}
/>
Even tried to swap TextInput with NumberInput
What happened instead: Now with this implementation, the moment the user starts typing in, if i am using NumberInput, after 3 char, when 4th number is pressed, it resets the input field. For Text Input, 4 numbers are formatted, with 5th number it resets
Steps to reproduce:
To login, just use any username password
https://codesandbox.io/s/condescending-moore-jri1ug?file=/src/posts.js:1424-1588
I have prepared a code sandbox where if you go to the Post Page and try to add he Min Revenue Filter and start tying in the value, you will see the issue after the 5th char is inputed.
Related code: https://codesandbox.io/s/condescending-moore-jri1ug?file=/src/posts.js:1424-1588
Environment
- React-admin version: ^3.9.0
- Last version that did not exhibit the issue (if applicable): Not Sure
- React version: 17
- Browser: Chrome
- Stack trace (in case of a JS error): No Error
Issue Analytics
- State:
- Created 2 years ago
- Comments:11 (3 by maintainers)
@CampingPanda You are a rockstar mate. Thank you so much for this help. This is exactly what i need. There is one caveat to this which i found when using the
parse
function now.I am writing a logic in parse function which would convert this generated string by
format
function to Integer again before it sends to the backend.But the
parse
function is overwriting whateverformat
does also in the UI. This mean the momentparse
function executes, it converts the string to Integer andformat
functions fails because it always expect thevalue
to be string. (.replaceAll only works with string and fails when it gets a number)So I modified the code a bit like below to handle number input in
format
functionWith this change, now i don’t need any change on the backend
Once again @CampingPanda many thanks for your help here. Really really appreciate
Since this issue has been clarified not to be a react-admin bug, I’m closing it.