React - how to forward reference to component

3 points
Created by:

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;
    // import React from 'react';
    // import ReactDOM from 'react-dom';
    const MyButton = React.forwardRef(({name}, ref) => {
        return (
            <button ref={ref}>{name}</button>
    const App = () => {
        const buttonRef = React.useRef();  // buttonRef.current property is <button> DOM element reference
        return (
              <MyButton ref={buttonRef} name="Click me!" />
    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.



    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.


    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.

    ❤️💻 🙂