As we know that uploading is a very important step in any application, so we can create a simple upload file button in ReactJS using the following approach. Material UI for React has this component available for us and it is very easy to integrate.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core npm install @material-ui/icons
Project Structure: It will look like the following.
Filename-App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react' ; import Button from '@material-ui/core/Button' ; import PhotoCamera from '@material-ui/icons/PhotoCamera' ; import IconButton from '@material-ui/core/IconButton' ; const App = () => { return ( <div style={{ display: 'flex' , margin: 'auto' , width: 400, flexWrap: 'wrap' , }}> <div style={{ width: '100%' , float: 'left' }}> <h3>How to use create button to choose file in ReactJS?</h3> <br /> </div> <input type= "file" accept= "image/*" style={{ display: 'none' }} id= "contained-button-file" /> <label htmlFor= "contained-button-file" > <Button variant= "contained" color= "primary" component= "span" > Upload </Button> </label> <h3> OR </h3> <input accept= "image/*" id= "icon-button-file" type= "file" style={{ display: 'none' }} /> <label htmlFor= "icon-button-file" > <IconButton color= "primary" aria-label= "upload picture" component= "span" > <PhotoCamera /> </IconButton> </label> </div> ); } export default App; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Now click on any of either button and now you can choose any file to upload. This is how we can create the upload file button in ReactJS.