To dynamically generate routes from an API response in React with React Router, follow these steps:
1. Fetch Routes Data from API
Assume the API returns a response like:
[
{ "path": "/home", "component": "Home" },
{ "path": "/about", "component": "About" },
{ "path": "/dashboard", "component": "Dashboard" }
]
2. Create Components
Define the components that will be rendered dynamically:
const Home = () => <h2>Home Page</h2>;
const About = () => <h2>About Page</h2>;
const Dashboard = () => <h2>Dashboard Page</h2>;
const componentsMap = {
Home,
About,
Dashboard
};
3. Fetch and Generate Routes in App.js
Use useEffect to fetch routes and dynamically render them:
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import { useEffect, useState } from "react";
const App = () => {
const [routes, setRoutes] = useState([]);
useEffect(() => {
fetch("/api/routes") // Replace with your API URL
.then((res) => res.json())
.then((data) => setRoutes(data));
}, []);
return (
<Router>
<Routes>
{routes.map(({ path, component }, index) => {
const Component = componentsMap[component];
return Component ? <Route key={index} path={path} element={<Component />} /> : null;
})}
</Routes>
</Router>
);
};
export default App;