Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
How to pass no arguments in forwardRef?

I have a custom component using using forwardRef() and I use it multiple times
like this:

const CustomComp = React.forwardRef(({props...},{ref1,ref2})=>{...}); //this is in another file


const CombinedRef={ref1:useRef(),ref2:useRef()};

<CustomComp ref={CombinedRef}/>  //case 1
<CustomComp/>  //case 2

but there are occasions where the custom component doesn't need a ref like in the second case
but if I don't pass the ref in case 2 it gives an error

null is not an object

so far my only solution has been <CustomComp ref={{}}/> //case 2
but is there a way where I don't have to pass ref in case 2 ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You cannot destructure your ref's directly if it should be an optional prop. So i shortly did a sandbox to show that... What you try right now is this:

const CustomComp = forwardRef((props, { ref1, ref2 }) => {
  console.log("ref1", ref1);
  console.log("ref2", ref2);
  return (
    <div {...props}>
      <span>CustomComp</span>
    </div>
  );
});

When you try to render that like this:

export default function App() {
  const ref1 = useRef();
  const ref2 = useRef();
  return (
    <div className="App">
      <CustomComp ref={{ ref1, ref2 }} />
      <CustomComp />
    </div>
  );
}

You get the error TypeError: Cannot destructure property 'ref1' of 'object null' as it is null.

But if you change it to this:

const CustomComp = forwardRef((props, ref) => {
  const { ref1, ref2 } = ref ? ref : {};
  console.log("ref1", ref1);
  console.log("ref2", ref2);
  return (
    <div {...props}>
      <span>CustomComp</span>
    </div>
  );
});

Then it starts working ;-)

Here is the sandbox: https://codesandbox.io/s/agitated-worker-pqjn3?file=/src/App.js:68-296

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda