If you are building any application which allows for user input and allows users to add images, you should support copy-pasting the image in the input area.
This is such a normal feature nowadays, Facebook uses it in its messenger and you can do the same on Whatsapp and other applications.
You can also implement multi-image uploads using this event by processing the image files yourself and showing them as small preview components above the message area. So a user can paste multiple images at once and still can type a message while the images are uploaded in the background.
It looks something like this
When a user pastes multiple images in the chat box, it processes them and shows a preview like the red boxes and allows the user to preview them or remove them.
This is arguably a much better user experience than having them upload the images one by one and wait for the images to upload.
So if you are working on a similar application, it's pretty easy to add this functionality.
So to begin with, all the DOM elements support an event called onPaste
, we can use this event specifically on the input and grab all the images from the clipboard.
<input onPaste={handleOnPaste}/>
Now we just need to handle the data when somebody presses CTRL + V
inside the input.
The function we pass to onPaste
gets an event
object which would have the pasted files
To get the files out of it we need to extract them with
const files = event.clipboardData.files;
const handleOnPaste = (event) => {
const { files } = event.clipboardData;
if (files) {
for (let i = 0; i < files.length; i++) {
// files[i] is the image blob, add it to your state or send it to the server
// or store them in state and show them as the preview
}
}
};
And that is the whole process, it's fairly easy to do and you can build complex UIs on top of it which feel responsive and up to date.
For more information check out MDN's docs: onPaste