// 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

      <label htmlFor="email">Add your email:</label>
      <input type="email" name="email" id="email" ref={forwardedRef}/>

// 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(){
  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"}

      {isModalOpened && <Modal forwardedRef={inputRef}/>}

// Parent component will receive as props the values or functions set for the ref on the child component
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