Loop through array to create routes in react router

I want to get into an API that returns me all the website routes I need for a responsive website.

I'm not really sure how to do this or even google it.

My code looks like this:

ReactDOM.render(
<Router history={browserHistory}>
    <Route path="/" component={App}>
      <IndexRoute pageId={5} background="" component={Home}/>
      <Route path="/your-journey" background="" pageId={7} component={YourJourney}/>
      <Route path="/designed-for-you" background="" pageId={6} component={DesignedForYou}/>
      <Route path="/join-us" background="" pageId={1} component={JoinUs}/>
      <Route path="/get-in-touch" background="no-hero-image" pageId={4} component={GetInTouch}/>
      <Route path="/legal-and-compliance" background="no-hero-image" pageId={8} component={Legal}/>
      <Route path="/privacy" background="no-hero-image" pageId={9} component={Privacy}/>
    </Route>
  </Router>,
  document.getElementById('root')
);

      

Where everything in the route path = "/" should come from the API.

+3


source to share


1 answer


Simple, just load the data into some action that loads your routes and displays the result in your function ReactDOM.render

. It will look something like this:



// This just maps the component string names (keys) to actual react components (values)
const COMPONENT_MAP = {
  'Privacy': Privacy, // quotes are not necessary, just illustrating the difference a bit more
  // ... other mappings
}

// Some asynch action that loads the routes from your API
getRoutes().then((routes) => {
  ReactDOM.render(
      <Router history={browserHistory}>
        <Route path="/" component={App}>
          <IndexRoute pageId={5} background="" component={Home}/>
          {routes.map((r) => {
             return <Route path={r.path} background={r.bg} pageId={r.pageId} component={COMPONENT_MAP[r.component]}/>
           }}
        </Route>
      </Router>,
      document.getElementById('root')
    );
});

      

+4


source







All Articles