Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router and pretty URLs

Tags:

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!

like image 400
sergei Avatar asked Apr 10 '17 10:04

sergei


2 Answers

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} />
like image 147
Chris Avatar answered Oct 14 '22 04:10

Chris


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.

like image 26
sergei Avatar answered Oct 14 '22 03:10

sergei