Fetching and Displaying All Drinks Using an API in React | Building a Cocktail App with React JS | Part 4

Posted by

Calling API to get & Show All Drinks on a Page in React | Cocktail App With React JS | Part 4

Calling API to get & Show All Drinks on a Page in React | Cocktail App With React JS | Part 4

In this tutorial, we will learn how to call an API to get a list of all drinks and display them on a page using React. We will be building a Cocktail App with React JS.

Step 1: Setting up the project

First, let’s create a new React project by running the following command:

npx create-react-app cocktail-app

Once the project is created, navigate to the project directory and install axios, a promise-based HTTP client for the browser and node.js, by running the following command:

npm install axios

Step 2: Calling the API

Next, let’s create a new component called DrinksList that will call the API to get the list of drinks. Create a new file called DrinksList.js in the src/components directory and add the following code:


import React, { useEffect, useState } from 'react';
import axios from 'axios';

const DrinksList = () => {
const [drinks, setDrinks] = useState([]);

useEffect(() => {
const fetchDrinks = async () => {
const response = await axios.get('https://www.thecocktaildb.com/api/json/v1/1/search.php?s=');
setDrinks(response.data.drinks);
};

fetchDrinks();
}, []);

return (

Drinks List

{drinks.map(drink => (

{drink.strDrink}

{drink.strDrink}

))}

);
};

export default DrinksList;

Step 3: Displaying the drinks

Now, let’s import the DrinksList component in the App.js file and render it inside the App component:


import React from 'react';
import './App.css';
import DrinksList from './components/DrinksList';

function App() {
return (

Cocktail App

);
}

export default App;

That’s it! You have now successfully called an API to get a list of all drinks and displayed them on a page using React. Stay tuned for the next part of this tutorial where we will add more functionality to our Cocktail App.