Table of Contents
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:
1body {2 margin: 1rem auto;3 display: flex;4 justify-content: center;5 max-width: 800px;6}78.App {9 display: flex;10 flex-direction: column;11 justify-content: center;12}1314button {15 margin-bottom: 1rem;16}
Creating the child component
Now create a child component with an input box:
1import React from "react"23const ChildComp = () => {4 return (5 <div>6 <input />7 </div>8 )9}1011export 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:
1import { useRef } from "react"2import ChildComp from "./ChildComp"34function App() {5 const childInputRef = useRef(null)67 return (8 <div className="App">9 <ChildComp childInputRef={childInputRef} />10 </div>11 )12}1314export default App
In the child component, we need to receive the passed prop and set it to the input element:
1import React from "react"23const ChildComp = ({ childInputRef }) => {4 return (5 <div>6 <input ref={childInputRef} />7 </div>8 )9}1011export 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:
1import { useRef } from "react"2import ChildComp from "./ChildComp"34function App() {5 const childInputRef = useRef(null)67 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}1718export 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!