DEV Community

Cover image for How to focus a child component input from parent component in React
collegewap
collegewap

Posted on • Edited on • Originally published at codingdeft.com

How to focus a child component input from parent component in React

In my previous article, I have discussed how to call a child component function from a parent component. In this article, we will see how to focus an input that is in the child component when a button in the parent component is clicked.

Project setup

Create a react project by running the following command:

npx create-react-app react-focus-child
Enter fullscreen mode Exit fullscreen mode

Update the index.css with the following styles:

body {
  margin: 1rem auto;
  display: flex;
  justify-content: center;
  max-width: 800px;
}

.App {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

button {
  margin-bottom: 1rem;
}
Enter fullscreen mode Exit fullscreen mode

Creating the child component

Now create a child component with an input box:

import React from "react"

const ChildComp = () => {
  return (
    <div>
      <input />
    </div>
  )
}

export default ChildComp
Enter fullscreen mode Exit fullscreen mode

Creating a ref and passing it to the child

We will be making use of the useRef hook to reference the child input box.
So let's create a reference in the parent component:

import { useRef } from "react"
import ChildComp from "./ChildComp"

function App() {
  const childInputRef = useRef(null)

  return (
    <div className="App">
      <ChildComp childInputRef={childInputRef} />
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

In the child component, we need to receive the passed prop and set it to the input element:

import React from "react"

const ChildComp = ({ childInputRef }) => {
  return (
    <div>
      <input ref={childInputRef} />
    </div>
  )
}

export default ChildComp
Enter fullscreen mode Exit fullscreen mode

Focusing the child input

Now in the parent component, let's create a button and add an onClick handler and focus the input:

import { useRef } from "react"
import ChildComp from "./ChildComp"

function App() {
  const childInputRef = useRef(null)

  const focusChild = () => {
    childInputRef.current && childInputRef.current.focus()
  }
  return (
    <div className="App">
      <button onClick={focusChild}>Focus child</button>
      <ChildComp childInputRef={childInputRef} />
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

Now if you test the application, you will be able to see that the input is focused when the button in the parent component is clicked.

Source code and Demo

You can download the source code here and view a demo here.

Top comments (0)