How do you implement set focus in an input using React-Hook-Form, this is what their FAQ's "How to share ref usage" code here https://www.react-hook-form.com/faqs/#Howtosharerefusage
import React, { useRef } from "react";
import { useForm } from "react-hook-form";
export default function App() {
const { register, handleSubmit } = useForm();
const firstNameRef = useRef();
const onSubmit = data => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input name="firstName" ref={(e) => {
register(e)
firstNameRef.current = e // you can still assign to ref
}} />
<input name="lastName" ref={(e) => {
// register's first argument is ref, and second is validation rules
register(e, { required: true })
}} />
<button>Submit</button>
</form>
);
}
I tried set focusing the ref inside useEffect but it doesn't work:
useEffect(()=>{
firstNameRef.current.focus();
},[])
Neither does inside the input:
<input name="firstName" ref={(e) => {
register(e)
firstNameRef.current = e;
e.focus();
}} />
Focus Something on Next Render with React Hooks It's set to false initially. Next, we add the toggleEditing function to call setEditing function to the negated value of the isEditing state. Then we create the inputRef ref that lets us assign to the input element below.
React Hook Form is focusing on uncontrolled inputs, which means you don't need to change the input value via state via onChange . This means you don't need value at all, and in fact, you only need to set defaultValue for the initial input value. import { useForm } from 'react-hook-form/dist/index.
setFocus:(name: string, options: SetFocusOptions) => void This method will allow users to programmatically focus on input. Make sure input's ref is registered into the hook form.
You can set the focus using the setFocus
helper returned by the useForm hook (no need to use a custom ref):
const allMethods = useForm();
const { setFocus } = allMethods;
...
setFocus('inputName');
https://react-hook-form.com/api/useform/setFocus
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With