Lokesh Bajracharya
Lokesh Bajracharya

Reputation: 540

React useRef to focus on next rendered input field

I want to focus on next input element added by Add button click

I have done a demo in codesandbox

Upvotes: 0

Views: 786

Answers (1)

Rohan Agarwal
Rohan Agarwal

Reputation: 2609

Try this:

useEffect(() => {
   if(ref.current) ref.current.focus();
  },[state])

  // adds new input handler
  const addObject = () => {
    setState([...state, { title: "" }]);
  };

The input element:

 <input type="text" ref={el => ref.current = el} value={item.title} />

State updates are async. So after updating your state its not guaranteed that the line following it will have the updated state.

Upvotes: 3

Related Questions