Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

172
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda