Languages
[Edit]
EN

React - how to forward reference to component

0 points
Created by:
Dirask Community
5460

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