// A Modal with input in it, that receives focus when it is mounted and displayed on screen // child component import {useEffect} from "react" export const Modal =({forwardedRef}) =>{ useEffect(()=> { // adding the focus() to the ref when component is mounting forwardedRef.current?.focus() },[forwardedRef]) return( <div> <label htmlFor="email">Add your email:</label> <input type="email" name="email" id="email" ref={forwardedRef}/> </div> ) } // parent component import {useRef, useState} from "react" import {Modal} from "./Modal" export default function App() { const [isModalOpened, setIsModalOpened] = useState(false) const inputRef = useRef() function handleModal(){ setIsModalOpened(!isModalOpened) } return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> <button type="button" onClick={handleModal}> {isModalOpened === true ? "Close modal" : "Open modal"} </button> {isModalOpened && <Modal forwardedRef={inputRef}/>} </div> ); } // Parent component will receive as props the values or functions set for the ref on the child component
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter