How would you dynamically generate routes from an API response

0 votes
Can i know How would you dynamically generate routes from an API response?
Feb 23 in Node-js by anonymous
• 19,190 points
59 views

1 answer to this question.

0 votes

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;

answered Feb 24 by Kavya

Related Questions In Node-js

0 votes
1 answer

How do you reinstall an app's dependencies using npm?

Hello @kartik, The easiest way is  to delete node_modules folder ...READ MORE

answered Jul 12, 2020 in Node-js by Niroj
• 82,840 points
2,838 views
0 votes
1 answer

How to execute an external program from within Node.js?

Hello @kartik, Exec has memory limitation of buffer ...READ MORE

answered Jul 17, 2020 in Node-js by Niroj
• 82,840 points
4,281 views
0 votes
1 answer

How to return data from Axios API?

Hello @kartik, The issue is that the original axiosTest() function ...READ MORE

answered Oct 13, 2020 in Node-js by Niroj
• 82,840 points
45,510 views
0 votes
1 answer

How to end an express.js / node POST response?

Hello @kartik, You can use res.end and pass in a ...READ MORE

answered Nov 30, 2020 in Node-js by Niroj
• 82,840 points
4,724 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP