Languages
[Edit]
EN

React - how to forward reference to component

0 points
Created by:
Giles-Whittaker
349

In this article, we would like to show you how to forward reference to a component in React.

TheĀ ref property is reserved by React so we are not able to pass it inside the component through theĀ props, so we use forwardRef, which wraps the component passingĀ as the second parameter after props referenceĀ from the outside of the component using ref property.

How below example works:

  1. Ā useRef - creates reference object,
  2. Ā forwardRef - forwards reference to the wrapped element,
  3. Ā buttonRefĀ - refers to the MyButton component,
  4. As a result the buttonRef should store a reference to the button's DOMĀ element after the component is rendered.

Practical example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const MyButton = React.forwardRef((props, ref) => (
  <button ref={ref}>Click me!</button>
));

const App = () => {
  const buttonRef = React.useRef();
  return (
    <div>
      <MyButton ref={buttonRef} />
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

References

ReactJS

React - forward reference to component
Native Advertising
šŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ā¤ļøšŸ’» šŸ™‚

Join