reactjs / reactjs/react.dev

[Docs] React.cloneElement and forwarding ref

Ouverte
#2,337 1 commentaire 0 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

Langage dominant
JavaScript
Étoiles
11.8k
Forks
7.9k
Merge moyen
1 j 11 h
PR mergées (30 j)
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?

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Piste de recherche

Examinez la section de l’API React cloneElement liée dans l’issue et comparez sa formulation concernant ref avec l’exemple ChangeTitle fourni. Précisez quel ref est conservé et comment React.forwardRef peut transmettre un ref ; le travail est terminé lorsque l’explication décrit précisément l’avertissement et l’utilisation corrigée.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
react
Domaine
documentation
Type d'issue
Documentation
Difficulté
2/5
Temps estimé
1-3 heures
Activité
À l'abandon
Clarté
Plutôt claire
Accessibilité débutants
48/100

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.