Search code examples
reactjsfocususe-effect

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()
})

Solution

  • 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