Created
September 22, 2022 00:06
-
-
Save rinfz/69f9f32a0a981952ac1b17f90b3df736 to your computer and use it in GitHub Desktop.
React hook form number control
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useForm, Controller } from "react-hook-form"; | |
const re = /^[-+]?\d*(\.\d*)?$/; | |
function NumCtrl({ name, onChange, value }: any) { | |
return <input | |
name={name} | |
value={value} | |
onChange={(e) => { | |
if (re.test(e.target.value)) onChange(e); | |
}} | |
type="text" | |
/> | |
} | |
function App() { | |
const { handleSubmit, control } = useForm(); | |
const onSubmit = (data: any) => { | |
console.log("form submitted: ", data); | |
} | |
return ( | |
<form onSubmit={handleSubmit(onSubmit)}> | |
<h1>NumCtrl example</h1> | |
<Controller | |
name="value" | |
control={control} | |
defaultValue="0" | |
render={({ field: { ref, ...rest } }) => ( | |
<NumCtrl {...rest} /> | |
)} | |
/> | |
<button type="submit">Submit</button> | |
</form> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment