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!
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} />
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With