Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: add focus to first child of a component which is a wrapper

If I have a component like

const Comp = ({children}) => {

    //some code
    return (
        <div> 
            {children}
        </div>
    )

}

and then call it like

<Comp>
    <input onChange={...} />
    <input onChange={...} />
</Comp>

How can I change the focus to the first input field of this component when the component renders, from within the Comp component.

Ideally I would like to have a useEffect function or something which looks something like

useEffect(() => {
   thisComponent.firstChild.focus()
})
like image 939
Sam Avatar asked Jan 30 '26 16:01

Sam


1 Answers

You need two things, useRef and useEffect, useRef for getting target element ref, and useEffect for handling focusing when then component renders.

children in a component props is an array, so you can manipulate it, you can use index to get which child element you want to set ref, and then call focus() by ref in useEffect:

function App(props) {
  const firstChildRef = useRef(null);

  useEffect(() => {
    if(firstChildRef.current) {
      firstChildRef.current.focus()
    }
  }, [firstChildRef])

  return (
    <div className="App">
      {props.children.map((child, index) => {
        if(index === 0) {
          return {...child, ref: firstChildRef};
        }
        return child;
      })}
    </div>
  );
}

Edit

like image 78
Wei Su Avatar answered Feb 03 '26 10:02

Wei Su



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!