Created
February 12, 2026 06:15
-
-
Save Gaurav8757/3c57c3a1645ababfbbb199272ec4421c to your computer and use it in GitHub Desktop.
forwardRef allows a parent component to send a ref to a child so the parent can directly access: a child DOM element or a child’s imperative methods.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Child Component (Custom Input + Auto Focus) | |
| // “forwardRef lets a parent component directly access a child’s DOM element or method through a ref, | |
| // which is not possible with normal props.” | |
| import React, { forwardRef } from "react"; | |
| const TextInput = forwardRef((props, ref) => { | |
| return <input ref={ref} {...props} />; | |
| }); | |
| export default TextInput; | |
| // Parent Uses the Child’s Input Ref | |
| import React, { useRef, useEffect } from "react"; | |
| import TextInput from "./TextInput"; | |
| const App = () => { | |
| const inputRef = useRef(); | |
| useEffect(() => { | |
| inputRef.current.focus(); // Parent focusing child’s input | |
| }, []); | |
| return ( | |
| <div> | |
| <TextInput ref={inputRef} placeholder="Auto focused input" /> | |
| </div> | |
| ); | |
| }; | |
| export default App; | |
| // Real Use Case Example: Open Child Modal from Parent | |
| // Child => modal | |
| const Modal = forwardRef((props, ref) => { | |
| const [open, setOpen] = useState(false); | |
| useImperativeHandle(ref, () => ({ | |
| show() { | |
| setOpen(true); | |
| }, | |
| hide() { | |
| setOpen(false); | |
| } | |
| })); | |
| return open ? <div className="modal">I am modal</div> : null; | |
| }); | |
| // Parent | |
| const App = () => { | |
| const modalRef = useRef(); | |
| return ( | |
| <> | |
| <button onClick={() => modalRef.current.show()}> | |
| Open Modal | |
| </button> | |
| // child modal pass ref={modalRef} | |
| <Modal ref={modalRef} /> | |
| </> | |
| ); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment