Reputation: 43
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.
Upvotes: 1
Views: 929
Reputation: 194
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
Upvotes: 1
Reputation: 202605
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 });
}
Upvotes: 1