$chiubaca / notes / fleeting / 2021-09-06
  • I never use ref forwarding in react, but itโ€™s a useful technique for transferring refs from another component into different component
  • By wrapping your component in a React.forwardRef function you can expose a ref.
    const FancyButton = React.forwardRef((props, ref) => (
      <button ref={ref} className="FancyButton">
        {props.children}
      </button>
    ));
    • We can then reference this ref outside of this component like so:
    // You can now get a ref directly to the DOM button:
    const ref = React.createRef();
    <FancyButton ref={ref}>Click me!</FancyButton>;
    • ref can passed around easily into any other component
Edit on GitHub โœ๏ธ

Hey I'm Alex Chiu ๐Ÿ‘‹. These are my notes for literally anything.

I'm using the Zettelkasten method to organise my thoughts here.

My more polished writings are published to my main blog at chiubaca.com

Follow me on: Github / X (Twitter) / Mastodon / LinkedIn