Skip to content

Instantly share code, notes, and snippets.

@rinfz
Created September 22, 2022 00:06
Show Gist options
  • Save rinfz/69f9f32a0a981952ac1b17f90b3df736 to your computer and use it in GitHub Desktop.
Save rinfz/69f9f32a0a981952ac1b17f90b3df736 to your computer and use it in GitHub Desktop.
React hook form number control
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