Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of API Routes in React JS. Let's get started 🚀
API Routes are the paths that your application uses to communicate with external data sources. In React JS, we often use API Routes to fetch, create, update, and delete data from servers. 🌐💻
API Routes allow our applications to interact with databases, third-party services, and other external data sources. This interaction is crucial for building dynamic, data-driven applications. 📊🔗
We'll be using React Router, a popular library for routing in React JS, to create our API Routes.
First, let's install React Router using npm:
npm install react-router-domNow, let's create a simple API Route that fetches data from an external source.
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
function UserProfile() {
const [user, setUser] = useState(null);
const { id } = useParams();
useEffect(() => {
fetch(`https://api.example.com/users/${id}`)
.then((response) => response.json())
.then((data) => setUser(data));
}, [id]);
if (!user) {
return <div>Loading...</div>;
}
return (
<div>
<h1>User Profile</h1>
<h2>ID: {user.id}</h2>
<h2>Name: {user.name}</h2>
{/* ... rest of the user's details */}
</div>
);
}
export default UserProfile;In this example, we're creating a UserProfile component that fetches user data based on the id provided in the URL. The useParams hook helps us access the URL parameters. 📝
Now, let's define a route for our UserProfile component in the main App component:
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import UserProfile from './UserProfile';
function App() {
return (
<Router>
<Switch>
<Route path="/user/:id" component={UserProfile} />
</Switch>
</Router>
);
}
export default App;Here, we're using the Switch component to define multiple routes, and the Route component to specify the path and component for each route. 📝
In a real-world project, you might need to create more complex API Routes for creating, updating, and deleting data. We'll cover these in future lessons. 🎯
What are API Routes used for in React JS?
We hope you enjoyed learning about API Routes in React JS! Stay tuned for more lessons on advanced topics. Happy coding! 🤖🚀