reactjs / reactjs/react.dev

[Docs] React.cloneElement and forwarding ref

Open
#2,337 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

Hi, I believe the documentation about React.cloneElement is not very clear about handling refs.

I am talking about that part: https://reactjs.org/docs/react-api.html#cloneelement

However, it also preserves refs. This means that if you get a child with a ref on it, you won’t accidentally steal it from your ancestor. You will get the same ref attached to your new element.

Now, let's see consider the following use case (simplified):

const ChangeTitle = ({ children, ...otherProps }) =>
  React.cloneElement(children, { 
    ...otherProps, 
    title: 'Title was changed'
  })

function MyComponent() {
  const myRef = React.useRef()
  return (
    <ChangeTitle ref={myRef}>
      <span>This is my component</span>
    </ChangeTitle>
  )
}

This throws a console warning about ChangeTitle unable to hold a ref.

In my original understanding of the docs, I though ChangeTitle would become the cloned element, which, as the docs explains, retain it's original ref, hance the one given by Mycomponent.

Instead, this is obviously wrong, and the cloned element would only retain a ref if it was given to itself, not the parent component, hence something like <span ref={spanRef}>This is my component</span>.

I guess the fix to the above code is the following:

const ChangeTitle = React.forwardRef(({ children, ...otherProps }, ref) =>
  React.cloneElement(children, { 
    ...otherProps, 
    ref,
    title: 'Title was changed'
  }))

Correct?

Is it worth adding specifically that cloneElement can contain the ref prop if used with React.forwardRef in a functional component?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Review the React API cloneElement section linked in the issue and compare its ref wording with the provided ChangeTitle example. Clarify which ref is retained and how React.forwardRef can pass a ref through; done when the explanation accurately describes the warning and corrected usage.

Written by the indexing model from the issue text.

Assessment

Tech stack
react
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.