Passing a ref as props
Mon Aug 15 2022 10:15:01 GMT+0000 (UTC)
Saved by
@jen_magpantay
#javascript
#react.js
// 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
content_copyCOPY
Comments