reactjs / reactjs/react.dev

[Docs] React.cloneElement and forwarding ref

Abierto
#2,337 1 comentario 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Lenguaje dominante
JavaScript
Estrellas
11.8k
Forks
7.9k
Merge medio
1 d 11 h
PR fusionados (30 d)
11

Descripción

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?

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Revisa la sección de la API de React cloneElement enlazada en el issue y compara la redacción sobre ref con el ejemplo de ChangeTitle proporcionado. Aclara qué ref se conserva y cómo React.forwardRef puede pasar un ref; se considera terminado cuando la explicación describe con precisión la advertencia y el uso corregido.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
react
Área
documentation
Tipo de issue
Documentación
Dificultad
2/5
Tiempo estimado
1-3 horas
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
48/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.