Show selected images from input type file – React

When using an input field where user can upload pictures or videos, it is a good practice to let the user view what files they have selected. In this article, we will discuss how you can show selected images using React.

Here we have simple input type file that accepts multiple image files.

<input type="file" multiple
    accept="image/*" />

Note that we do not specify the “name” attribute. This is intentional, because we will be managing the selected files manually. If you put the “name” attribute as well, then it will cause confusion on server side.

We will create an array that holds all the user selected files in a React state variable.

const [images, setImages] = React.useState([]);

Then we will update it’s value whenever user select files from input field.

<input type="file" multiple
    accept="image/*"
    onChange={ function (event) {
        setImages(Array.from(event.target.files));
    } } />

Array.from is a Javascript built-in method used to convert any array-like object into an array. Now we need to find a way to view the selected images.

{ images.map(function (image, index) {
    return (
        <div key={ `image-${ index }` }>
            <img src={ URL.createObjectURL(image) } />

            <button type="button"
                onClick={ function () {
                    const temp = [ ...images ];
                    temp.splice(index, 1);
                    setImages(temp);
                } }>Remove</button>
        </div>
    );
}) }

Note that we also created a delete button which when clicked, will remove that image from the array. It will not delete the file from input type file, because the FileList used by input field is read-only. However, we will manage that manually.

Now let me show you, how you can attach those images to your AJAX request. We will create a button which when clicked will call a function.

<button type="button"
    onClick={ function () {
        submit();
    } }>Submit</button>

We will create that function in our React component.

function submit() {
    const formData = new FormData();

    images.map(function (image) {
        formData.append("images[]", image);
    });

    const ajax = new XMLHttpRequest();
    ajax.open("POST", "data.php", true);
    ajax.send(formData);
}

This will loop through all the images and append them in FormData object as an array. That was the reason we did not set the “name” attribute on input type file. If we set the name attribute, then it will send 2 different names for the same thing which will cause confusion.

That’s how you can show selected images from input type file using React. If you want to achieve this using plain HTML and Javascript, check our this tutorial.