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