How to use imgur to host images in ReactsJS ?
Imgur is primarily used as an image-sharing service, where users post content through an interface provided by the company, just like Facebook or Instagram. But we can also post images to Imgur by accessing their APIs. So, in this article, we will discuss how to upload images to Imgur in React without relying on any other third-party library like Axios.
Prerequisite:
Approach :
To use imgur to host images in React we will use the POST method in the fetch API to send and update data on imgur. We will get a image file input and send the input data to imgur using API to host images.
Steps to Create React Application:
Step 1: Create a new React application using the following command.
npx create-react-app react-imgur
Step 2: Now move into the project folder and start the React app.
cd react-imgurnpm
Project Structure:
Step 3: Now let’s see how to register Imgur application. Visit https://imgur.com/register to create a new user account.
Step 4: After verifying your account, visit https://api.imgur.com/oauth2/addclient to register for a new application.
Step 5: Go the application submenu for managing the Client ID
Example: This example implements image hosting on imgur using POST request to the API.
Javascript
// Filename - App.js import { useState } from "react" ; function App() { const [file, setFile] = useState(); const onFileChange = (event) => { // Updating the state setFile({ file: event.target.files[0] }); }; const onFileUpload = async () => { // Client ID const clientId = "fd2e1e3d3d12ce1" , auth = "Client-ID " + clientId; // Creating an object of formData const formData = new FormData(); // Adding our image to formData formData.append( "file" , file); // Making the post request await fetch( "https://api.imgur.com/3/image/" , { // API Endpoint method: "POST" , // HTTP Method body: formData, // Data to be sent headers: { // Setting header Authorization: auth, Accept: "application/json" , }, }) // Handling success .then( (res) => alert( "image uploaded" ) && console.log(res) ) . catch ( (err) => alert( "Failed" ) && console.log(err) ); }; return ( <> <input name= "file" type= "file" onChange={onFileChange} /> <button onClick={onFileUpload}>Upload</button> </> ); } export default App; |
Step to run the application: Open the terminal and type the following command.
npm start
Ŏutput: Run the application and navigate to http://localhost:3000/