Home > Enterprise >  How to use React.forwardRef?
How to use React.forwardRef?

Time:01-10

I want to pass ref to a child component with forwardRef, but current for the given ref is always null. Why?

Consider this simple example:

// Details.jsx
import { useRef, forwardRef } from 'react';

const Details = () => {
    const usernameRef = useRef(null);

    const InputClipboardButton = React.forwardRef((props, ref) => (
        <ClipboardButton targetInputRef={ref} />
    ));

    return (
        <div>
            <input type="text" ref={usernameRef} />
            <InputClipboardButton ref={usernameRef} />
        </div>
    );
};
// ClipboardButton.jsx
const ClipboardButton = ({ targetInputRef }) => {
    const copyToClipboard = () => {
        console.log(targetInputRef);
    }

    <button onClick={copyToClipboard}>
        Copy
    </button>
}; 

CodePudding user response:

When using forwardRef you must be mindful of the order of the parameters passed (props and ref):

You can define the component like so:

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

Note how forwardRef takes two parameters:

  1. The props
  2. The ref being forwarded

You may also destructure the props value, as well as call the ref property a different name:

const FancyButton = React.forwardRef(({
  btnType,
  children
}, forwardedRef) => (
  <button ref={forwardedRef} type={btnType} className="FancyButton">
    {children}
  </button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref} btnType="button">Click me!</FancyButton>;

Example adapted from React Docs

CodePudding user response:

Clipboard Button is a component, so you must use forwardRef in this component as well

    const ClipboardButton = forwardRef((props,ref) => {
        const copyToClipboard = () => {
           console.log(ref);
        }

        <button onClick={copyToClipboard}>
            Copy
        </button>
   }); 
  • Related