Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: how to set focus on last input after adding it?

Tags:

reactjs

can you please help me figure out how to set focus on last input after adding it by click on button?

function InputList() {
  const [items, setItems] = useState([]);
  const add = useCallback(() => setItems([...items, {id: uniqId()}]), [items]);

  return (
    <div>
      {items.map(item => <input key={item.id}/>)}
      <button onClick={add} type="button">Add</button>
    </div>
  );
}
like image 677
redexp Avatar asked Nov 24 '25 23:11

redexp


1 Answers

easiest way is to pass the same ref to all the inputs:

const refToLast = React.createRef();
useEffect(() => {
  refToLast.current.focus();
});
...
      {items.map(item => <input ref={refToLast} key={item.id}/>)}
...

But we may found that we setting focus to last input on each re-rendering(even when we type some value). So we may add condition to set focus only when items.length is changed:

useEffect(() => {
  refToLast.current.focus();
}, [items.length]);

But that would also run when we remove entry not adding them. Not sure if that's desired.

[upd] to skip setting focus on initial rendering we can add additional flag:

const doSetAutoFocus = useRef(false);

useEffect(() => {
  refToLast.current.focus();
}, [items.length, doSetAutoFocus]);

const onAddClicked = useCallback(() => {
  add();
  doSetAutoFocus.current = true;
}, [add])
like image 172
skyboyer Avatar answered Nov 27 '25 13:11

skyboyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!