Passing ref as props, using forwardRef and useRef

PHOTO EMBED

Mon Aug 15 2022 09:06:42 GMT+0000 (UTC)

Saved by @jen_magpantay #javascript #react.js

// child component
import {forwardRef} from "react"

export const Button = forwardRef(({...props}, ref) => {
return <button ref={ref} id="buttonId-js" {...props}>Button</button>
})

// parent component
import {useRef} from "react"
import { Button } from "./Button";

export default function App() {
const buttonRef = useRef()
return (
<div className="App">
    <h1>Hello CodeSandbox</h1>
    <h2>Start editing to see some magic happen!</h2>
    <Button ref={buttonRef} onClick={()=> console.log(buttonRef.current.id)}
        />
</div>
);
}

// buttonRef.current gives access nodes and DOM, allowing to change the component
// useRef should be used in uncontrolled components - those ones that are not handled by React states or handle functions
content_copyCOPY