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
Is there a way to dynamically access a ref's properties in react?

I have a form with four file inputs. Different inputs for files with different purposes.

I have created a ref for each file.

I have created an array of the refs.

On submit, I was trying to access all of the refs and get their ref.current.files[0].

Example Code Below:

import {useRef} from 'react';

export default function myComponent(props){

const file1 = useRef(null);
const file2 = useRef(null);
const file3 = useRef(null);
const file4 = useRef(null);

const fileRefs = [file1, file2, file3, file4];

function onSubmit(){
  let files = [];

  fileRefs.map((ref) => {
    let obj = {};
    obj.fileName = ref.current.files[0].name;
    obj.file = ref.current.files[0];
    files.push(obj)
  })
}

render(
<div className="form">

<label>File 1 </label>
<input type="file" ref={file1} />

<label>File 2 </label>
<input type="file" ref={file2} />

<label>File 3 </label>
<input type="file" ref={file3} />

<label>File 4 </label>
<input type="file" ref={file4} />

<button onClick={() => onSubmit()}>Submit</button>

</div>
)
}

Error: "TypeError: Cannot read properties of null (reading 'files')"

So, I can't access the .current property of a ref in this manner.

I don't really know how to approach this issue, was just trying to cobble something together.

If anyone could help me out with a way of dynamically accessing a ref's current properties, that would be great.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I don't see an issue in your code, per se, it works if you select a file for all file inputs. The issue only manifests if any input is left without a selected file.

To resolve this you can use the Optional Chaining operator to do a null check into the file object.

ref.current.files[0]?.name

If ref.current.files[0] is null or undefined then access into the file object is short-circuited and undefined is returned, otherwise, access is continued and the file name is returned.

Code:

function onSubmit() {
  const files = fileRefs.map((ref) => ({
    fileName: ref.current.files[0]?.name,
    file: ref.current.files[0],
  }));

  console.log({ files });
}

Edit is-there-a-way-to-dynamically-access-a-refs-properties-in-react

about 4 years ago · Juan Pablo Isaza Denunciar

0

In your code instead of render use return, you have used functional component where render function is not available. Check this link for working solution https://codesandbox.io/s/wonderful-faraday-upg89?file=/src/App.js

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