fixing NumberComponent rendering

This commit is contained in:
Mose Müller 2023-08-02 12:06:21 +02:00
parent e7b003d396
commit 42bfa028e0

View File

@ -98,6 +98,7 @@ const handleDeleteKey = (
}; };
export const NumberComponent = React.memo((props: NumberComponentProps) => { export const NumberComponent = React.memo((props: NumberComponentProps) => {
const { name, parent_path, readOnly, docString } = props;
const renderCount = useRef(0); const renderCount = useRef(0);
// Create a state for the cursor position // Create a state for the cursor position
const [cursorPosition, setCursorPosition] = useState(null); const [cursorPosition, setCursorPosition] = useState(null);
@ -107,19 +108,23 @@ export const NumberComponent = React.memo((props: NumberComponentProps) => {
useEffect(() => { useEffect(() => {
renderCount.current++; renderCount.current++;
// Set the cursor position and input string after the component re-renders // Parse the input string to a number for comparison
const numericInputString =
props.type === 'int' ? parseInt(inputString) : parseFloat(inputString);
// Update inputString only when value is different from numericInputString
// preventing the removal of trailing decimals or zeros after the decimal.
if (props.value !== numericInputString) {
setInputString(props.value.toString());
}
// Set the cursor position after the component re-renders
const inputElement = document.getElementsByName(name)[0] as HTMLInputElement; const inputElement = document.getElementsByName(name)[0] as HTMLInputElement;
if (inputElement && cursorPosition !== null) { if (inputElement && cursorPosition !== null) {
// Setting input string as trailing zeros after the decimal will be stripped
// otherwise
inputElement.value = inputString;
inputElement.setSelectionRange(cursorPosition, cursorPosition); inputElement.setSelectionRange(cursorPosition, cursorPosition);
} }
}); });
const { name, parent_path, value, readOnly, docString } = props;
const handleNumericKey = (key: string, value: string, selectionStart: number) => { const handleNumericKey = (key: string, value: string, selectionStart: number) => {
// Check if a number key or a decimal point key is pressed // Check if a number key or a decimal point key is pressed
if (key === '.' && (value.includes('.') || props.type === 'int')) { if (key === '.' && (value.includes('.') || props.type === 'int')) {
@ -217,7 +222,7 @@ export const NumberComponent = React.memo((props: NumberComponentProps) => {
<InputGroup.Text>{name}</InputGroup.Text> <InputGroup.Text>{name}</InputGroup.Text>
<Form.Control <Form.Control
type="text" type="text"
value={value} value={inputString}
disabled={readOnly} disabled={readOnly}
name={name} name={name}
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}