sergei
sergei

Reputation: 1176

react-router and pretty URLs

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!

Upvotes: 5

Views: 5037

Answers (2)

sergei
sergei

Reputation: 1176

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.

Upvotes: 2

Chris
Chris

Reputation: 6176

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} />

Upvotes: 2

Related Questions