Languages
[Edit]
EN

React - how to forward reference to component

3 points
Created by:
Giles-Whittaker
589

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. To solve the problem we can use forwardRef() function, which wraps the component passing as the second argument ref property.

    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}>{props.name}</button>
    ));
    
    const App = () => {
      const buttonRef = React.useRef();
      return (
        <div>
          <MyButton ref={buttonRef} name="Click me!" />
        </div>
      );
    };
    
    const root = document.querySelector('#root');
    ReactDOM.render(<App />, root);

    In the above example:

    1. useRef - creates reference object,
    2. buttonRef - stores MyButton component reference (in our case it is reference to <button> DOM element),
    3. forwardRef - forwards reference to the wrapped component.

     

    References

    Donate to Dirask
    Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
    Join to our subscribers to be up to date with content, news and offers.

    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