Skip to content
react

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

Apr 1, 2023Abhishek EH2 Min Read
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:

1npx create-react-app react-focus-child

Update the index.css with the following styles:

index.css
1body {
2 margin: 1rem auto;
3 display: flex;
4 justify-content: center;
5 max-width: 800px;
6}
7
8.App {
9 display: flex;
10 flex-direction: column;
11 justify-content: center;
12}
13
14button {
15 margin-bottom: 1rem;
16}

Creating the child component

Now create a child component with an input box:

ChildComp.js
1import React from "react"
2
3const ChildComp = () => {
4 return (
5 <div>
6 <input />
7 </div>
8 )
9}
10
11export default ChildComp

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:

App.js
1import { useRef } from "react"
2import ChildComp from "./ChildComp"
3
4function App() {
5 const childInputRef = useRef(null)
6
7 return (
8 <div className="App">
9 <ChildComp childInputRef={childInputRef} />
10 </div>
11 )
12}
13
14export default App

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

ChildComp.js
1import React from "react"
2
3const ChildComp = ({ childInputRef }) => {
4 return (
5 <div>
6 <input ref={childInputRef} />
7 </div>
8 )
9}
10
11export default ChildComp

Focusing the child input

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

App.js
1import { useRef } from "react"
2import ChildComp from "./ChildComp"
3
4function App() {
5 const childInputRef = useRef(null)
6
7 const focusChild = () => {
8 childInputRef.current && childInputRef.current.focus()
9 }
10 return (
11 <div className="App">
12 <button onClick={focusChild}>Focus child</button>
13 <ChildComp childInputRef={childInputRef} />
14 </div>
15 )
16}
17
18export default App

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.

Do follow me on twitter where I post developer insights more often!

© 2024 CodingDeft.Com