This React js tutorial will carry you towards the important concept of how to upload a single file and multiple files in the React js application and also how to preview it. Here are the topics we are going to cover apart from how to upload file in react js:
- React js file upload
- React js file upload example
- React js file upload example with axios
- React js file upload validation
- React js file upload with preview
- Upload multiple files in react js
- Multiple file uploads in react js with preview
- Drag and drop multiple file uploads in react js
React js file upload
Here we will see how to upload a file in react js or handle react js file in the application.
Uploading different types of files is a critical component that any developer must consider while developing an application. It is a necessary requirement for developing a comprehensive application. When a user uploads files to a server from a client machine, this is referred to as file uploading.
The procedure of uploading a file is broken into two phases:
- Choose a File (user Input): The first step is to add the tag to our App component to allow the user to select a file. This tag’s type attribute should be set to “file.” We now require an event handler to monitor any changes made to the file. When the user picks a new file, this event handler is called and the state is updated.
- Send the following request to the server: After storing the chosen file (in the state), we must now send it to a server. We can use fetch or Axios for this purpose. (We utilize Axios, a promise-based HTTP client for the browser, and NodeJS in this code.) The file is wrapped in a FormData object and sent to the service.
Read Form validation in react js
React js file upload example
Here we see an example of how to create a File upload component.
Example 1: React js simple file upload
For example, we will create a simple form in react js that will have a field to upload a file.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js file contains the below code:
import './App.css';
import FileUploadPage from './FileUpload';
function App() {
return (
<div className="App">
<FileUpload></FileUpload>
</div>
);
}
export default App;
In the FileUpload component, write the code below to create a simple form with one input field.
import React from 'react';
function FileUpload() {
const handleUpload =() => {
alert("File uploaded")
};
return (
<div className="App">
<form onSubmit={handleUpload}>
<h1>Upload a file</h1>
<input type="file" />
<button type="submit">Upload</button>
</form>
</div>
);
}
export default FileUpload;
Now run the application with the npm start command, and you can see the form render on the page, having a field that will accept the file. As there is no file chosen so it is showing ‘No file chosen’.
To upload a file click on ‘Choose file’, then select the file from the local desktop. Once you choose a file click on the upload icon, and you will get a successful message ‘ File uploaded’
Example 2: Form with file upload in react js with state
Here we will use the above form with file upload to keep track of what file is uploading.
For example, to keep track of the file our user chooses to upload, we’ll build a state variable, an onChange event handler for the input element, and a handle change method.
In the above File upload component, write the below code:
import React, {useState} from 'react';
function FileUpload() {
const [selectedFile, setSelectedFile] = useState();
const[isSelected, setIsSelected]= useState(false)
// const [isFilePicked, setIsFilePicked] = useState(false);
const handleChange = (event) => {
setSelectedFile(event.target.files[0]);
setIsSelected(true);
};
const handleSubmit = () => {
if(isSelected=== true){
alert("File uploded");
} else{
alert("upload a file");
}
};
return(
<form>
<h2>Upload a file</h2>
<input type="file" name="file" onChange={handleChange} />
{isSelected ? (
<div>
<h2>File Details</h2>
<p>Filename: {selectedFile.name}</p>
<p>Filetype: {selectedFile.type}</p>
<p>Size in bytes: {selectedFile.size}</p>
<p>
lastModifiedDate:{' '}
{selectedFile.lastModifiedDate.toLocaleDateString()}
</p>
</div>
) : (
<p>Select a file to show details</p>
)}
<div>
<button onClick={handleSubmit}>Submit</button>
</div>
</form>
)
}
export default FileUpload;
Now run the application with the npm start command and you can see the form render on the page having a file input field. As there is no file chosen so it is showing ‘No file chosen. To upload a file click on ‘Choose file’, then choose the file from the local desktop.
Once the file is uploaded you can see the file details. You click on the Submit, and you can see the message is pop on the screen ‘File uploaded.
Read Components in React js
React js file upload example with Axios
Here we will see how to upload files in React js with Axios.
What are the Axios in React?
- Axios is used to communicate with the backend, and it also supports the native JS ES6 Promise API.
- It is a library that is used to create API requests, get data from the API, and then perform actions with that data in our React application.
- Axios is a popular HTTP client (with 78k stars on Github) that allows us to make HTTP queries directly from the browser.
Why do we want Axios in react?
Axios, a well-known library, is mostly used to send asynchronous HTTP queries to REST endpoints. This library is really useful for performing CRUD activities.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js file contains the below code:
import './App.css';
import FileUploadPage from './FileUpload';
function App() {
return (
<div className="App">
<FileUpload></FileUpload>
</div>
);
}
export default App;
The FileUpload component contains the below code:
import React, {Component} from 'react';
import axios from 'axios';
class FileUpload extends Component {
state = {
// Initially, no file is selected
onSelectedFile: null
};
// On file select (from the pop up)
onFileChange = event => {
// Update the state
this.setState({ onSelectedFile: event.target.files[0] });
};
// On file upload (click the upload button)
onFileUpload = () => {
// Create an object of formData
const formData = new FormData();
// Update the formData object
formData.append(
"myFile",
this.state.onSelectedFile,
this.state.onSelectedFile.name
);
// Details of the uploaded file
console.log(this.state.onSelectedFile);
// Request made to the backend api
// Send formData object
axios.post("api/uploadfile", formData);
};
// File content to be displayed after
// file upload is complete
fileData = () => {
if (this.state.onSelectedFile) {
return (
<div>
<h2>File Information:</h2>
<p>File Name: {this.state.onSelectedFile.name}</p>
<p>File Type: {this.state.onSelectedFile.type}</p>
<p>
Last Modified:{" "}
{this.state.onSelectedFile.lastModifiedDate.toDateString()}
</p>
</div>
);
} else {
return (
<div>
<br />
<h4>Choose file before Pressing the Upload button</h4>
</div>
);
}
};
render() {
return (
<div>
<h3>
File Upload with Axios
</h3>
<div>
<input type="file" onChange={this.onFileChange} />
<button onClick={this.onFileUpload}>
Upload!
</button>
</div>
{this.fileData()}
</div>
);
}
}
export default FileUpload;
Now run the application with the npm start command and you can see the form render on the page with the file input field. Click on the choose file, then you can see the details.
This is an example of React js file upload example with Axios.
Read What is JSX in React js
React js file upload validation
Here we will see how to validate the image file in React js.
So here we will use the antd library for form and date picker in our react application. For this we need to install it by using the below command
npm install antd
For example, we will create an application that will only accept the png file, and if you will upload any other format, you will get an error message on the window.
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js file contains the below code:
import React, { useState } from 'react';
import './App.css';
//Bootstrap and jQuery libraries
import 'bootstrap/dist/css/bootstrap.min.css';
//Image upload modules
import { Upload, Button, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import "antd/dist/antd.css";
class App extends React.Component {
render(){
const Uploader = () => {
const [fileList, updateFileList] = useState([]);
const props = {
fileList,
beforeUpload: file => {
//File Type Check
if (file.type !== 'image/png') {
message.error(`${file.name} is not a png file`);
}
return file.type === 'image/png';
},
onChange: info => {
console.log(info.fileList);
// file.status is empty when beforeUpload return false
updateFileList(info.fileList.filter(file => !!file.status));
},
};
return (
<Upload {...props}>
<Button icon={<UploadOutlined />}>Upload png only</Button>
</Upload>
);
};
return (
<>
<div className="MainDiv">
<div className="jumbotron text-center">
<h3>spguides.com</h3>
<br></br>
</div>
<div className="container">
<Uploader />
</div>
</div>
</>
);
}
}
export default App;
Now run the application with the npm start command and you can upload a png file it will accept.
This is an example of how to validate image file in react js.
Read Props in React js
React js file upload with preview
Here we will see how to upload a file and preview it using react js.
Example 1: React js image file upload with preview
For example, We’ll see how to easily add an image file from our local device to our React project. We may accomplish this by creating a static method URL. createObjectURL().
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js file contains the below code:
import './App.css';
import FileUploadPage from './FileUpload';
function App() {
return (
<div className="App">
<FileUpload></FileUpload>
</div>
);
}
export default App;
The FileUpload component contains the below code:
import React, { useState } from "react";
function FileUpload() {
const [selectFile, setSelectFile] = useState();
function handleChange(e) {
console.log(e.target.files);
setSelectFile(URL.createObjectURL(e.target.files[0]));
}
return (
<div className="App">
<h2>Choose an Image:</h2>
<input type="file" onChange={handleChange} />
<img src={selectFile} alt="" />
</div>
);
}
export default FileUpload;
Now run the application with the npm start command and you can see the input field will render on the page. Next, choose one image file, you want to preview.
This is an example of how to preview the uploaded file.
Example 2: React js excel file upload with preview
Here we will see how to upload and preview excel files in React js.
I needed a quick, easy way to render and display Excel spreadsheets on a webpage, but I was not able to find a pre-developed JavaScript library. The only option was to upload the file to Google Drive or Microsoft OneDrive, then embed the link.
If only there was a more elegant and user-friendly solution to this problem. It’s called react excel render library.
What is the react-excel-render library?
React-Excel-Renderer is a React-based component for rendering and displaying Excel spreadsheets on a webpage.
To use the React-excel-renderer library, we need to install it in our application by using the below command:
npm install react-excel-renderer --save
We will use the two modules from react-excel-renderer, these are:
- Excelrender: To transform sheet data into JSON format, import the primary module ExcelRenderer.
- OutTable: we will import OutTable as well to show the acquired JSON in an HTML table.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js file contains the below code:
import './App.css';
import FileUploadPage from './FileUpload';
function App() {
return (
<div className="App">
<FileUpload></FileUpload>
</div>
);
}
export default App;
The FileUpload component contains the below code:
import {OutTable, ExcelRenderer} from 'react-excel-renderer';
import React,{Component} from 'react';
class FileUpload extends Component {
state={
rows:"",
cols:""
}
handleFile = (event) => {
let filesObj = event.target.files[0];
//just pass the filesObj as parameter
ExcelRenderer(filesObj, (err, resp) => {
if(err){
console.log(err);
}
else{
this.setState({
cols: resp.cols,
rows: resp.rows
});
}
});
}
render() {
return (
<div>
<h2> Upload a excel file</h2>
<input type="file" onChange={this.handleFile.bind(this)} />
<div>
{this.state.rows && <OutTable data= {this.state.rows} columns={this.state.cols}
tableClassName="ExcelTable2007" tableRowHeaderClass="heading"></OutTable>}
</div>
</div>
)
}
}
export default FileUpload;
Now run the application with the npm start command and you can see the field to upload a file. Click on the choose file option and then choose excel file. You can preview the excel file.
This is an example of how to preview uploaded excel file.
Example 3: React js pdf file upload with preview
Here we will see how to upload the pdf file and preview it using react js.
To preview pdf in react js, we need to use React PDF Viewer library.
What is React Pdf viewer?
The React PDF Viewer is a lightweight and flexible component that allows you to view and print PDF files. With key activities like zooming, scrolling, text searching, text selection, and text copying, it gives the greatest viewing experience available. The thumbnail, bookmark, hyperlink, and table of contents capability facilitate navigating both within and outside of PDF files.
To use in our application we need to install react pdf viewer core, by using the below command:
npm install @react-pdf-viewer/core
Also, we will use the defaultLayout plugin, which will add a toolbar and a sidebar with the following tabs
- A tab that displays thumbnails of pages
- Outline bookmarks are listed in a tab.
- A tab for attachments
To use this plugin we need to install it in our application, by using the below command:
npm install '@react-pdf-viewer/default-layout';
Now, we will see how to apply the logic to preview the pdf in react js application.
Let’s say the index.html contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js file contains the below code:
import './App.css';
import FileUploadPage from './FileUpload';
function App() {
return (
<div className="App">
<FileUpload></FileUpload>
</div>
);
}
export default App;
The FileUpload component contains the below code:
import React,{useState} from 'react'
// Import the main component
import { Viewer } from '@react-pdf-viewer/core';
// Plugins
import { defaultLayoutPlugin } from '@react-pdf-viewer/default-layout';
// Import the styles
import '@react-pdf-viewer/core/lib/styles/index.css';
import '@react-pdf-viewer/default-layout/lib/styles/index.css';
// Worker
import { Worker } from '@react-pdf-viewer/core';
export const FileUpload = () => {
// Create new plugin instance
const defaultLayoutPluginInstance = defaultLayoutPlugin();
// for onchange event
const [selectPdfFile, setSelectPdfFile]=useState(null);
const [pdfFileError, setPdfFileError]=useState('');
// for submit event
const [viewPdf, setViewPdf]=useState(null);
// onchange event
const fileObj=['application/pdf'];
const handleFileChange=(e)=>{
let selectedFile=e.target.files[0];
if(selectedFile){
if(selectedFile&&fileObj.includes(selectedFile.type)){
let reader = new FileReader();
reader.readAsDataURL(selectedFile);
reader.onloadend = (e) =>{
setSelectPdfFile(e.target.result);
setPdfFileError('');
}
}
else{
setSelectPdfFile(null);
setPdfFileError('Please select valid pdf file');
}
}
else{
alert('select pdf file');
}
}
// form submit
const handleSubmit=(e)=>{
e.preventDefault();
if(selectPdfFile!==null){
setViewPdf(selectPdfFile);
}
else{
setViewPdf(null);
}
}
return (
<div className='container'>
<h1> Upload a pdf file</h1>
<br></br>
<form className='form-group' onSubmit={handleSubmit}>
<input type="file" className='form-control'
required onChange={handleFileChange}
/>
{pdfFileError&&<div className='error-msg'>{pdfFileError}</div>}
<br></br>
<button type="submit" className='btn btn-success btn-lg'>
UPLOAD
</button>
</form>
<br></br>
<h4>View PDF</h4>
<div className='pdf-container'>
{/* show pdf conditionally (if we have one) */}
{viewPdf&&<><Worker workerUrl="https://unpkg.com/pdfjs-dist@2.16.105/build/pdf.worker.min.js">
<Viewer fileUrl={viewPdf}
plugins={[defaultLayoutPluginInstance]} />
</Worker></>}
{/* if we dont have pdf or viewPdf state is null */}
{!viewPdf&&<>No pdf file choosen </>}
</div>
</div>
)
}
export default FileUpload
Now run the application with the npm start command and you can see the file field render on the page. Next click on the choose file option, then select a pdf file and click on upload. Now you can preview the content on the page.
This is an example of how to preview an uploaded pdf file.
Read State in React js
React js multiple file upload
Here we will see how to apply multiple file uploads in React js.
In this example, we will see how to upload multiple files to the React application
So the index.html file contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js file contains the below code:
import './App.css';
import FileUploadPage from './FileUpload';
function App() {
return (
<div className="App">
<FileUpload></FileUpload>
</div>
);
}
export default App;
The FileUpload component contains the below code:
import { useState } from 'react';
const MaxFile = 5;
function FileUpload() {
const [uploadedFiles, setUploadedFiles] = useState([])
const [fileLimit, setFileLimit] = useState(false);
const handleUploadFiles = files => {
const uploaded = [...uploadedFiles];
let limitExceeded = false;
// check if the file is already exists
files.some((file) => {
if (uploaded.findIndex((f) => f.name === file.name) === -1) {
uploaded.push(file);
if (uploaded.length === MaxFile) setFileLimit(true);
//limit the number of file to be uploaded
if (uploaded.length > MaxFile) {
alert(`You can only add a maximum of $ MaxFile} files`);
setFileLimit(false);
limitExceeded = true;
return true;
}
}
})
if (!limitExceeded) setUploadedFiles(uploaded)
}
const fileEventHandler = (e) => {
const chosenFiles = Array.prototype.slice.call(e.target.files)
handleUploadFiles(chosenFiles);
}
return (
<div className="App">
{/* display the uploaded files */}
<h2>Upload a file</h2>
<input id='fileUpload' type='file' multiple
accept='application/pdf, image/png'
onChange={fileEventHandler}
disabled={fileLimit}
/>
<label htmlFor='fileUpload'>
<a className={`btn btn-primary ${!fileLimit ? '' : 'disabled' } `}>Upload</a>
</label>
<div className="uploaded-files-list">
{uploadedFiles.map(file => (
<div >
{file.name}
</div>
))}
</div>
</div>
);
}
export default FileUpload;
Now run the application with the npm start command, and you can see the input field that will access the multiple files. So, click on chosen Files, and choose multiple file .
This is how we can upload multiple files in react js.
Read State in React js Hooks
Multiple image file uploads in react js with preview
Here we will show to preview multiple image files, by uploading them.
In this example, we will see how to preview numerous images before uploading in react js by following a few basic steps.
As you are aware, if you upload one or more photographs by selecting them from your computer’s locale directory, you will only see the total amount of files beneath the file input Field.
If you pick 5 photographs from your local computer, you will see “5 files” to the right of the browse Input field.
Following that, with the total amount of files, it will be easier to reconfirm the selected photographs before uploading. However, if you provide numerous image previews, you can quickly determine which photographs are chosen to upload to the server.
Before we will start this example we need to install bootstrap, for styling, so here we will use bootstrap 4. To install it in the project, run the below command:
npm install bootstrap
So the index.html file contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js file contains the below code:
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import FileUpload from './FileUpload';
function App() {
return (
<div className='App'>
<h2> Multiple Image Upload With Preview</h2>
<FileUpload></FileUpload>
</div>
);
}
export default App;
The FileUpload component contains the below code:
import { useState } from "react";
import ImagePrew from "./ImagePrew";
function FileUpload(){
const [img, setImg] = useState([]);
const handleMultipleImg =(event)=>{
const selectedFIles =[];
const targetFiles =event.target.files;
const targetFilesObj= [...targetFiles]
targetFilesObj.map((file)=>{
return selectedFIles.push(URL.createObjectURL(file))
})
setImg(selectedFIles);
}
return(
<>
<div className="form-group my-3 mx-3">
<input type="file" onChange={handleMultipleImg} multiple/>
</div>
<ImagePrew img={img} />
</>
)
}
export default FileUpload
The Imageprew file contains the below code:
import React from "react";
function ImagePrew({img}){
return(
<div className="row">
{
img.map((url)=>{
return (
<div className="col-sm-1">
<div className="card">
<img src={url} alt=""/>
</div>
</div>
)
})
}
</div>
)
}
export default ImagePrew;
Now run the application with the npm start command and you can see the choose file field, which will accept multiple image files, once you choose the file, you can preview it.
So, click on Choose File option and choose multiple images then you can see the number of files and you can preview it.
This is how we can preview multiple uploaded image file in react js.
Read Handling Events in React js
Drag and drop multiple file uploads in react js
Here we will see how to drag and drop multiple file uploads in react js.
Applications that use drag-and-drop functionality on browsers are known as drag-and-drop platforms. The user clicks and drags files to a droppable element (drop zone) using a mouse or touchpad, then releases the mouse button to release the files.
For example, we will create a component that listens for drag events, manages drops, and reverts to the standard file picker.
For this we will use React Dropzone library, which is used to create intricate drag-and-drop user interfaces while maintaining the destructured nature of your components, React-dropzone is a collection of React modules. Drag-and-drop in React is most frequently used for three things: uploading files, reorganising images/files, and moving data between various folders.
To use React Dropzone library in the application, we need to install it by using the below command.
npm install react-dropzone
Now let’s how to create an application with drag-drop functionality.
So the index.html file contains the below code:
<div id="root"></div>
The Index.js file is the starting point of the React app, so it contains the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
The App.js file contains the below code:
import axios from 'axios';
import DragDrop from './DragDrop';
import React,{Component} from 'react';
class App extends Component {
state = {
// Initially, no file is selected
onSelectedFile: null
};
// On file select (from the pop up)
handleFileChange = event => {
// Update the state
this.setState({ onSelectedFile: event.target.files[0] });
};
// On file upload (click the upload button)
handleFileUpload = () => {
// Create an object of formData
const formData = new FormData();
// Update the formData object
formData.append(
"myFile",
this.state.onSelectedFile,
this.state.onSelectedFile.name
);
// Details of the uploaded file
console.log(this.state.onSelectedFile);
// Request made to the backend api
// Send formData object
axios.post("api/uploadfile", formData);
};
// File content to be displayed after
// file upload is complete
fileData = () => {
if (this.state.onSelectedFile) {
return (
<div>
<h2>File Details:</h2>
<p>Name of File: {this.state.onSelectedFile.name}</p>
<p>File Type: {this.state.onSelectedFile.type}</p>
<p>
Last Modified:{" "}
{this.state.onSelectedFile.lastModifiedDate.toDateString()}
</p>
</div>
);
} else {
return (
<div>
</div>
);
}
};
render() {
return (
<div>
<h3>
File Uploading!
</h3>
<div>
<DragDrop />
</div>
{this.fileData()}
</div>
);
}
}
export default App;
The DragDrop component contains the below code:
import React from "react";
import { useDropzone } from "react-dropzone";
function DragDrop({ open }) {
const { getRootProps, getInputProps, isDragOn, acceptedFiles } =
useDropzone({});
const files = acceptedFiles.map((file) => (
<li key={file.path}>
{file.path} - {file.size} bytes
</li>
));
return (
<div {...getRootProps({ className: "dropzone" })}>
<input className="input-zone" {...getInputProps()} />
<div className="text-center">
{isDragOn ? (
<p className="dropzone-content">
Release to drop the files here
</p>
) : (
<p className="dropzone-content">
Drag & drop some files here, else click to select files
</p>
)}
<button type="button" onClick={open} className="btn">
To select files, click on the button
</button>
</div>
<aside>
<ul>{files}</ul>
</aside>
</div>
);
}
export default DragDrop;
To style the Drag and drop area, add the below CSS code to the index.css.
body {
text-align: center;
padding: 20px;
border: 3px blue dashed;
width: 60%;
margin: auto;
}
Now run the application with npm start command and you can see the area where you can drop the files or else select the file.
This is how we can drag and drop the multiple files in react js.
Conclusion
This reacts js tutorial concluded with how we can upload single or multiple files in react js using state and different types of libraries. Also, we discussed different types of examples:
- React js file upload
- React js file upload example
- React js file upload example with Axios
- React js file upload validation
- React js file upload with preview
- How to upload multiple files in react js
- Multiple file uploads in react js with preview
- Drag and drop multiple file uploads in react js
You may like the following react js tutorials:
- Conditional rendering react js
- React js form examples for beginners
- How to reset form in react js
I am Bijay a Microsoft MVP (10 times – My MVP Profile) in SharePoint and have more than 17 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com