Home Web Front-end JS Tutorial ree APIs for Your Next Projects

ree APIs for Your Next Projects

Aug 13, 2024 pm 12:48 PM

ree APIs for Your Next Projects

1. Mapbox API Example

Mapbox offers comprehensive tools and accurate location data that you can use to create maps, navigation services, and other location-based applications. With Mapbox, you can display custom maps, integrate geolocation, and much more.
Link

import React, { useEffect } from 'react';

const Mapbox = () => {
    useEffect(() => {
        // Set your Mapbox access token here
        const mapboxAccessToken = 'YOUR_MAPBOX_ACCESS_TOKEN';

        // Create a map instance
        const map = new mapboxgl.Map({
            container: 'map', // Container ID in the HTML
            style: 'mapbox://styles/mapbox/streets-v11', // Style URL
            center: [-74.5, 40], // Starting position [lng, lat]
            zoom: 9, // Starting zoom
        });

        mapboxgl.accessToken = mapboxAccessToken;
    }, []);

    return (
        <div>
            <h2>Mapbox Example</h2>
            <div id="map" style={{ width: '100%', height: '400px' }}></div>
        </div>
    );
};

export default Mapbox;
Copy after login

2. NASA API Example

The NASA API provides access to a wealth of data related to space, including images, videos, and information about planets, stars, and more. Whether you’re building an educational tool or just want to display fascinating space data, NASA’s API is an excellent resource.
Link

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

const Nasa = () => {
    const [data, setData] = useState(null);

    useEffect(() => {
        axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')
            .then(response => setData(response.data))
            .catch(error => console.error('Error fetching data from NASA API:', error));
    }, []);

    return (
        <div>
            <h2>NASA Astronomy Picture of the Day</h2>
            {data ? (
                <div>
                    <h3>{data.title}</h3>
                    <img src={data.url} alt={data.title} style={{ maxWidth: '100%' }} />
                    <p>{data.explanation}</p>
                </div>
            ) : (
                <p>Loading...</p>
            )}
        </div>
    );
};

export default Nasa;
Copy after login

3. Favorite Quotes API Example

This API offers a collection of insightful quotes that you can easily integrate into your application. It’s perfect for creating apps that inspire and motivate users.
Link

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

const Quotes = () => {
    const [quote, setQuote] = useState('');

    useEffect(() => {
        axios.get('https://favqs.com/api/qotd')
            .then(response => setQuote(response.data.quote.body))
            .catch(error => console.error('Error fetching data from Quotes API:', error));
    }, []);

    return (
        <div>
            <h2>Quote of the Day</h2>
            <blockquote>{quote}</blockquote>
        </div>
    );
};

export default Quotes;
Copy after login

4. Edamam API Example

Edamam provides access to a comprehensive database of food items and recipes, along with detailed health analyses. This API is ideal for creating diet trackers, recipe apps, and nutrition-based applications.
Link

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

const Edamam = () => {
    const [recipes, setRecipes] = useState([]);
    const query = "chicken"; // Example search query

    useEffect(() => {
        const appId = 'YOUR_EDAMAM_APP_ID';
        const appKey = 'YOUR_EDAMAM_APP_KEY';

        axios.get(`https://api.edamam.com/search?q=${query}&app_id=${appId}&app_key=${appKey}`)
            .then(response => setRecipes(response.data.hits))
            .catch(error => console.error('Error fetching data from Edamam API:', error));
    }, []);

    return (
        <div>
            <h2>Edamam Recipes for "{query}"</h2>
            <ul>
                {recipes.map((recipe, index) => (
                    <li key={index}>
                        <img src={recipe.recipe.image} alt={recipe.recipe.label} width="50" />
                        {recipe.recipe.label}
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default Edamam;
Copy after login

5. Fake Store API Example

The Fake Store API is a fantastic tool for developers working on e-commerce projects. It provides pseudo-real data that you can use to populate your store with products, prices, and categories.
Link

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

const FakeStore = () => {
    const [products, setProducts] = useState([]);

    useEffect(() => {
        axios.get('https://fakestoreapi.com/products')
            .then(response => setProducts(response.data))
            .catch(error => console.error('Error fetching data from Fake Store API:', error));
    }, []);

    return (
        <div>
            <h2>Fake Store Products</h2>
            <ul>
                {products.map(product => (
                    <li key={product.id}>
                        <img src={product.image} alt={product.title} width="50" />
                        {product.title}
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default FakeStore;
Copy after login

6. Pokémon API Example

The Pokémon API (PokeAPI) is a must-have for any Pokémon fan. It offers comprehensive data on all Pokémon, including stats, types, and abilities, making it perfect for building Pokémon-related apps and games.
Link

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

const Pokemon = () => {
    const [pokemonList, setPokemonList] = useState([]);

    useEffect(() => {
        axios.get('https://pokeapi.co/api/v2/pokemon?limit=10')
            .then(response => setPokemonList(response.data.results))
            .catch(error => console.error('Error fetching data from Pokémon API:', error));
    }, []);

    return (
        <div>
            <h2>Pokémon List</h2>
            <ul>
                {pokemonList.map((pokemon, index) => (
                    <li key={index}>
                        {pokemon.name}
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default Pokemon;
Copy after login

7. IGDB API Example

The Internet Games Database (IGDB) API provides data on thousands of video games, allowing you to create video game-oriented websites and applications. You can fetch information about games, platforms, genres, and more.
Link

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

const IGDB = () => {
    const [games, setGames] = useState([]);

    useEffect(() => {
        const apiKey = 'YOUR_IGDB_API_KEY';

        axios.post('https://api.igdb.com/v4/games/', 
        'fields name, cover.url; sort popularity desc; limit 10;', 
        { headers: { 'Client-ID': 'YOUR_CLIENT_ID', 'Authorization': `Bearer ${apiKey}` } })
            .then(response => setGames(response.data))
            .catch(error => console.error('Error fetching data from IGDB API:', error));
    }, []);

    return (
        <div>
            <h2>Popular Video Games</h2>
            <ul>
                {games.map(game => (
                    <li key={game.id}>
                        {game.cover ? <img src={game.cover.url} alt={game.name} width="50" /> : null}
                        {game.name}
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default IGDB;
Copy after login

Conclusion

Each of these examples shows how to integrate the respective APIs into a React, Next. You can easily extend these examples to fit your application’s needs, whether it’s displaying more detailed information, handling user interactions, or styling the output for better UX.

These examples demonstrate how straightforward it is to fetch and display data from various free APIs.

The above is the detailed content of ree APIs for Your Next Projects. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Zustand asynchronous operation: How to ensure the latest state obtained by useStore? Zustand asynchronous operation: How to ensure the latest state obtained by useStore? Apr 04, 2025 pm 02:09 PM

Data update problems in zustand asynchronous operations. When using the zustand state management library, you often encounter the problem of data updates that cause asynchronous operations to be untimely. �...

See all articles