reactjs / reactjs/react.dev

[Suggestion]: Documentation for `useRef` should tell us how to deal with multiple refs on a single element

Aberta
#7,251 2 comentários 1 reação 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

type: documentation
Linguagem predominante
JavaScript
Estrelas
11.8k
Forks
7.9k
Merge médio
1d 11h
PRs com merge (30d)
11

Descrição

Summary

Sometimes you need to add more than one ref to a single element. For example:

  • When using forwardRef you need to pass the forwarded ref to whatever element, but you also need your own ref attached to the same element.
  • When using useController of react-hook-form, you get a ref you need to pass to the input element for focus management, but you also need your own ref for doing other things with that same input element.

This is an issue that is not even mentioned on the current documentation of useRef. I've been using gregberge/react-merge-refs to deal with this, but after I added the recommended eslint-plugin-react-compiler, this method now generates a warning:

Ref values (the current property) may not be accessed during render.

If you're not allowed to access ref values during render to merge them, then how are you supposed to attach multiple refs to a single element now?

The documentation needs to tell us how to do this properly, and in a way that doesn't break the compiler or generate warnings in your eslint plugins.

Page

https://react.dev/reference/react/useRef

Details

Example component needing this:

export default forwardRef(
  function BaseCheckbox(
    { label, indeterminate = false, onChange, onCheckedChange, ...props },
    ref
  ) {
    const inputId = useId();
    const inputRef = useRef(null);

    useLayoutEffect(() => {
      if (inputRef.current)
        inputRef.current.indeterminate = indeterminate;
    }, [indeterminate]);

    return (
      <div className="checkbox">
        <input
          type="checkbox"
          id={inputId}
          /**
           * Here we have two refs we need to attach to this input, but there's no
           * documented way to do that and the undocumented way is not allowed
           * according to the new rules from `eslint-plugin-react-compiler`.
           */ 
          ref={mergeRefs(inputRef, ref)}
          onChange={(e) => {
            onChange?.(e);
            onCheckedChange?.(e.currentTarget.checked);
          }}
          aria-checked={
            indeterminate ? 'mixed' : props.checked ? 'true' : 'false'
          }
          {...props}
        />
        <label htmlFor={inputId}>
          {label}
        </label>
      </div>
    );
  }
);

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Comece pela página de referência atual de useRef em https://react.dev/reference/react/useRef e analise como ela aborda refs durante a renderização. Investigue as questões relacionadas a multiple-ref e eslint-plugin-react-compiler descritas na issue e, em seguida, atualize a documentação para que a abordagem compatível e o comportamento esperado do compilador fiquem claros.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
react
Domínio
documentation
Tipo de issue
Documentação
Dificuldade
4/5
Tempo estimado
3-5 dias
Status de atividade
Pouca atividade
Clareza
Razoavelmente clara
Facilidade para iniciantes
55/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.