'How to round up number inside HTMLInputElement
I have an Input field to which if I enter a decimal value I want to round it off to its next highest number, but the problem is that whenever I type a dot (".") the onChnage gets triggered, rounds it off and then updates the value, so basically I'm not able to type anything after the dot ("."). I can't use onBlur here, can someone tell me what I can do
import React, { useState, ChangeEvent } from 'react';
import { TextInputHelperCurrency } from '@honeycomb-npm/honeycomb-react';
export type LoanAmountProps = {
label: string;
errorMessage: string;
defaultLoanAmount: string;
minLoanAmount: string;
maxLoanAmount: string;
};
const LoanAmount: React.VFC = () => {
const [enteredLoanAmount, setEnteredLoanAmount] = useState<string>('10000');
const handleAmountChange = (value: string) => {
const roundedUpValue = Math.ceil(Number(value));
setEnteredLoanAmount(String(roundedUpValue));
};
return (
<div className="loan-amount">
<TextInputHelperCurrency
data-testid="textInputHelperCurrency"
id="loanAmount"
value={enteredLoanAmount}
onChange={handleAmountChange}
/>
</div>
);
};
export default LoanAmount;
Solution 1:[1]
I haven't worked on ReactTS, but I will answer the solution in ReactJS. Feel free to edit the solution or suggest changes for TS.
Firstly, create a useRef hook which will be passed in the TextInputHelperCurrency as innerRef prop. Next, in useEffect hook, check if the useRef hook created above has loaded and if there is a click, and useRef hook does not contains the target event Node, then round up the value.
In the TextInputHelperCurrency component, accept innerRef as prop and attach the innerRef as ref to the parent tag of return statement. Here is the code:
const LoanAmount: React.VFC = () => {
const [enteredLoanAmount, setEnteredLoanAmount] = useState<string>('10000');
const textInputRef = useRef(null);
useEffect(() => {
const handleOutsideClickEvent = (event) => {
if (
textInputRef.current &&
!textInputRef.current.contains(event.target)
) {
const roundedUpValue = Math.ceil(Number(textInputRef.current.value));
setEnteredLoanAmount(String(roundedUpValue));
}
};
document.addEventListener('click', handleOutsideClickEvent);
return () => document.removeEventListener('click', handleOutsideClickEvent);
}, [textInputRef]);
return (
<div className='loan-amount'>
<TextInputHelperCurrency
data-testid='textInputHelperCurrency'
id='loanAmount'
value={enteredLoanAmount}
innerRef={textInputRef}
/>
</div>
);
};
Inside TextInputHelperCurrency component,
const TextInputHelperCurrency = ({innerRef}) => {
// some code
return (
<div ref={innerRef}>
{/* some more code */}
</div>
)
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aditya |
