Sunday, November 17, 2024
Google search engine
HomeLanguagesHow to use imgur to host images in ReactsJS ?

How to use imgur to host images in ReactsJS ?

ReactJS is an open-source front-end JavaScript library for building user interfaces or UI components. It is the most popular frontend library in the market and is maintained by Facebook Corporation. Alan Schaaf founded Imgur in 2009 as an image hosting platform. Like Reddit, uploaded images can be upvoted or downvoted by other users.

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:

Creating React Application:

Step 1: Create a new React application using the following command.

npx create-react-app react-imgur

 

 

Project Structure: It will look like the following. 

 

Step 2: Now move into the project folder and start the react app.

cd react-imgur
npm start

 

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

 

Step 6: Remove everything from the App component  in project_folder/src/App.js.

 

Step 7: Declare a new state file using useState hook to store our file before sending POST request.

const [file, setFile] = useState();

Step 8: Create an input field that will take the image file as the input.

<input type="file" onChange={onFileChange} />

Step 9: Create an onFileChange function that will work as an event handler to listen any changes made to the file.

  const onFileChange = event => {
   // Updating the state
   setFile({ file: event.target.files[0] });
 };

Step 10: Create onFileUpload function that will upload our image to the imgur server. This process can be divided into four steps: 

  • Create a new formdata.
  • Prepare a new request with Client ID and formdata.
  • Send the post request.
  • Handle the response.
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",
    },
  })
    .then((res) => alert("image uploaded") && console.log(res)) // Handling success
    .catch((err) => alert("Failed") && console.log(err)); // Handling error
};

Step 11: Add a button that will trigger the onFileUpload function.

<button onClick={onFileUpload}>Upload</button>

Step 12: At this point your App.js should look like.

Complete Code: 

Javascript




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/

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments