5

What is the best way to use react-router with pretty URLs? All URLs are stored in DB (total amount about 400,000). When I follow link I need to resolve component for rendering from the server by AJAX request and render it.

Thanks!

sergei
  • 1,006
  • 8
  • 17
  • Possible duplicate of [How to Implement dynamic routing in routes.js for generated menu items in sidebar in universal react redux boilerplate by erikras](http://stackoverflow.com/questions/35764510/how-to-implement-dynamic-routing-in-routes-js-for-generated-menu-items-in-sideba) – James Donnelly Apr 10 '17 at 10:30

2 Answers2

2

React router can take dynamic values which can be database driven.

For example, if you have a database of products, you can have a Link like this:

<Link to="/products/1234/product_name">Product</Link>

And your component would be defined like this:

<Route path="/products/:id/:url_title" component={Products} />
Chris
  • 5,310
  • 5
  • 21
  • 28
  • The pathnames in your example have defined structure. I said about pathnames like this: `/buy-iphone7-red` or `/buy-apple-macbook-retina-13`. – sergei Apr 18 '17 at 10:17
  • I see. In which case you could probably go with something like `` – Chris Apr 18 '17 at 10:41
  • I have `400,000` `URLs` in my `DB`. It's not a good idea. I posted an answer which resolves this issue. Thanks! – sergei Apr 18 '17 at 10:47
2

I found an answer for the question. With react-router you could dynamically resolve component with getComponent method of Route. For example:

import ProductPage from '...'
import CategoryPage from '...'

const MAP_PAGE_TYPE_TO_COMPONENT = {
    'productPage': ProductPage,
    'categoryPage': CategoryPage

};

....

const getComponent = (location, callback) => {
  requestToServer(location.pathname)
    .then(function(response){
      const Component = MAP_PAGE_TYPE_TO_COMPONENT[response.pageType];
      callback(null, <Component items = { response.items } />);
     })
    .catch(callback)
};

....

<Route 
  path='*'
  getComponent = { getComponent }
/>

You should call callback function with null as first parameter if there is no error, and <Component /> as second parameter.

sergei
  • 1,006
  • 8
  • 17