how to format value on fly with react hook form?
- User
how to format value on fly with react hook form?
- Assistant
To format a value on the fly with React Hook Form, you can use the
setValuemethod provided by the library.Here is an example of how you can format a currency value on the fly using React Hook Form:
jsximport React from 'react'; import { useForm } from 'react-hook-form'; const App = () => { const { register, setValue } = useForm(); const handleInputChange = (e) => { const value = parseFloat(e.target.value.replace(/[^0-9.]/g, '')); const formattedValue = value.toLocaleString('en-US', { style: 'currency', currency: 'USD' }); setValue('amount', formattedValue); }; return ( <form> <label htmlFor="amount">Amount:</label> <input type="text" id="amount" name="amount" onChange={handleInputChange} ref={register} /> </form> ); }; export default App;