/ React

Handling Paths in React Application

When using React Router, "a" components should be replaced by Link:

<Link to="/about">About</Link>
<Link to={`/${post.categorySlug}/${post.slug}`}>{post.name}</Link>

Passing a route to Link as string works, but doesn't protect us from mistyping. Also changing routes is not very easy. For example if we decide that /${post.categorySlug}/${post.slug} should become /posts/${post.slug}, there would be a lot of grepping.

Ruby on Rails solves those problems by generating a method for every route your application.

This concept works great with React Router:

<Link to={paths.about()}>About</Link>
<Link to={paths.post(post)}>{post.name}</Link>

All you have to do is define all your routes in file:

// routes.js
export default {
   post(post) {
     return `/${post.categorySlug}/${post.slug}`;
   },

   about() {
    return '/about';
   },

   // not all routes are strings
   contacts() {
     return { pathname: 'contacts', state: { modal: true } }; 
   },

   // helper for image sources
   image(path) {
     return `https://product-hunt-cdn.com/images/${path}`
   }

   // ....
};

This technique works great with flow, giving you type safety in your links.

I have thought several times about generating this file from router component. But didn't have a chance to do so and with React Router v4 this won't be very easy.