In this tutorial, we will learn how to call an API to get a list of cocktails from a server using React Js. We will be building a Cocktails App that displays a list of cocktails fetched from an API and allows the user to view details of each cocktail.
Step 1: Setting up the project
First, create a new React Js project using create-react-app. Open your terminal and run the following commands:
npx create-react-app cocktails-app
cd cocktails-app
Step 2: Install Axios
To make HTTP requests to the server, we will use Axios. Run the following command to install Axios:
npm install axios
Step 3: Create a Component to display Cocktails
Create a new file named CocktailList.js inside the src/components directory. Add the following code to CocktailList.js:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const CocktailList = () => {
const [cocktails, setCocktails] = useState([]);
useEffect(() => {
axios.get('https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita')
.then((res) => {
setCocktails(res.data.drinks);
})
.catch((error) => {
console.error(error);
});
}, []);
return (
<div>
<h1>Cocktails</h1>
<ul>
{cocktails.map((cocktail) => (
<li key={cocktail.idDrink}>{cocktail.strDrink}</li>
))}
</ul>
</div>
);
};
export default CocktailList;
Step 4: Update the App Component
Open the src/App.js file and update it as follows:
import React from 'react';
import CocktailList from './components/CocktailList';
function App() {
return (
<div className="App">
<CocktailList />
</div>
);
}
export default App;
Step 5: Run the Application
Finally, run the following command to start the React development server:
npm start
Open your browser and go to http://localhost:3000 to see the Cocktails App in action. You should see a list of cocktails fetched from the server displayed on the screen.
That’s it! You have successfully built a Cocktails App that fetches data from a server using React Js. Feel free to customize the app further by adding more features like searching for specific cocktails or displaying cocktail details on a separate page. Happy coding!