Read multiple files using an input in React

To read multiple files in React, you need to create an <input></input> component with type = 'file' and set it as multiple.

For example:

jsx
import React from 'react';

const Multiple = () => {
    
    const upload = (e) => {
        
        // Convert the FileList into an array and iterate
        Array.from(e.target.files).forEach(file => {
            
            // Define a new file reader
            let reader = new FileReader();
            
            // Function to execute after loading the file
            reader.onload = () => console.log(reader.result);
            
            // Read the file as a text
            reader.readAsText(file);
            
        });
        
    }
    
    return(
        <input onChange = {upload} type = 'file' multiple/>
    );
    
}

export default Multiple;

To do it asynchronously:

jsx
import React from 'react';

const Multiple = () => {
    
    const upload = async (e) => {
        
        // Convert the FileList into an array and iterate
        let files = Array.from(e.target.files).map(file => {
            
            // Define a new file reader
            let reader = new FileReader();
            
            // Create a new promise
            return new Promise(resolve => {
                
                // Resolve the promise after reading file
                reader.onload = () => resolve(reader.result);
                
                // Reade the file as a text
                reader.readAsText(file);
                
            });
            
        });
        
        // At this point you'll have an array of results
        let res = await Promise.all(files);
        
    }
    
    return(
        <input onChange = {upload} type = 'file' multiple/>
    );
    
}

export default Multiple;

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.