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
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;
}
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
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
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
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
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.
Top comments (0)