All Projects → tricoder42 → Named Urls

tricoder42 / Named Urls

Licence: mit
Simple named url patterns in Javascript

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Named Urls

Chat Buy React
Client for beginners to learn, built with React / Redux / Node
Stars: ✭ 1,026 (+1325%)
Mutual labels:  react-router
Simple Universal React Redux
The simplest possible Async Universal React & Redux Boilerplate app, that works on both Mac and Windows
Stars: ✭ 58 (-19.44%)
Mutual labels:  react-router
React Router Ga
Google Analytics component for React Router
Stars: ✭ 66 (-8.33%)
Mutual labels:  react-router
React Hackernews
HackerNews clone built with React, ReactRouter & Redux, with full page server-side rendering
Stars: ✭ 49 (-31.94%)
Mutual labels:  react-router
React Cool Starter
😎 🐣 A starter boilerplate for a universal web app with the best development experience and a focus on performance and best practices.
Stars: ✭ 1,083 (+1404.17%)
Mutual labels:  react-router
React Router Form
<Form> is to <form> as <Link> is to <a>
Stars: ✭ 58 (-19.44%)
Mutual labels:  react-router
React Redux Antdesign Webpack Starter
react + redux + ant design + react-router 4 + webpack 4 starter
Stars: ✭ 44 (-38.89%)
Mutual labels:  react-router
Dva React Worms
dva新手综合教程
Stars: ✭ 70 (-2.78%)
Mutual labels:  react-router
Egg React Typescript Boilerplate
Egg React TypeScript Server Side Render (SSR) / Client Side Render (CSR)
Stars: ✭ 56 (-22.22%)
Mutual labels:  react-router
Starter React Flux
Generate your React PWA project with TypeScript or JavaScript
Stars: ✭ 65 (-9.72%)
Mutual labels:  react-router
React 5ddm
5d动漫,使用React,服务端渲染,接口(不开源)来自赞片CMS。仅供参考,交流群:14646823 欢迎加入
Stars: ✭ 50 (-30.56%)
Mutual labels:  react-router
Piwik React Router
Piwik analytics component for react-router
Stars: ✭ 53 (-26.39%)
Mutual labels:  react-router
Dva Starter
完美使用 dva react react-router,最好用的ssr脚手架,服务器渲染最佳实践
Stars: ✭ 60 (-16.67%)
Mutual labels:  react-router
Create React Redux App
This project was bootstrapped with Create React App and Redux, Sass Structure.
Stars: ✭ 46 (-36.11%)
Mutual labels:  react-router
Ssr React
How to server-side render React, hydrate it on the client and combine client and server routes
Stars: ✭ 67 (-6.94%)
Mutual labels:  react-router
React Antd Admin Template
一个基于React+Antd的后台管理模版,在线预览https://nlrx-wjc.github.io/react-antd-admin-template/
Stars: ✭ 1,022 (+1319.44%)
Mutual labels:  react-router
React Movies App
🎥 React movie app finder || experimenting with ant-design
Stars: ✭ 58 (-19.44%)
Mutual labels:  react-router
Pierfrancescosoffritti.com
Personal website.
Stars: ✭ 70 (-2.78%)
Mutual labels:  react-router
Spring React Boilerplate
Boilerplate application to demonstrate how to wire up Spring, JWT Authentication, React, Redux and Websockets
Stars: ✭ 70 (-2.78%)
Mutual labels:  react-router
Koa React Notes Web
🤓 A simple SPA built using Koa (2.5.1) as the backend and React (16.4.1) as the frontend. Features MySQL integration, user authentication, CRUD note actions, and more.
Stars: ✭ 61 (-15.28%)
Mutual labels:  react-router

named-urls

Simple named url patterns in JavaScript.


CircleCI Code Coverage PRs Welcome MIT License

Watch on GitHub Star on GitHub Tweet

Implementing a static route config and named routes on top of (react-router) at this point is like a 20 line ordeal. – Ryan Florence

Motivation

Named routes are essential to keep route config DRY and prevent silly errors due to typos. This feature was removed from react-router in 1.0 and I missed it since then as many others.

There're other libs dealing with named routes, some of them provide custom Link, Route routes, some of them have more features to integrate with express. Here's incomplete list of libs I considered before writing these 20 lines of code (and 200+ lines of other files to publish this package):

NOTE: v2 introduces breaking changes. Please check out the migration guide before upgrading.

Installation

$ npm install named-urls

or

$ yarn add named-urls

Quickstart

Create file with all routes in your application (e.g. routes.js). Use named-urls/include to create namespaced group of routes with common prefix:

// routes.js
import { include } from 'named-urls'

export default {
   // simple route
   profile: '/profile',

   // route with params
   article: '/article/:articleId',

   // route with optional params
   messages: '/messages/:messageId?',

   // Routes with common path prefix
   auth: include('/auth', {
      // Absolute url (ignore /auth prefix)
      login: '/login/',

      // Relative urls (prefixed with /auth)
      passwordReset: 'password/reset/',
      passwordVerify: 'password/verify/',
   }),

   // Routes with params
   messages: include('/messages', {
      all: '',
      unread: 'unread/',

      // nesting of includes is allowed
      detail: include(':messageId/', {
         show: '',
         edit: 'edit/',
         comments: 'comments/',
      })
   })
}

Use routes in Route component from react-router-dom:

// App.js

import React from 'react'
import { Switch, Route } from 'react-router-dom'

import routes from './routes'
import * as scenes from './scenes' // just a convention, could be "pages"

function App() {
   return (
      <Switch>
         <Route path={routes.profile} component={scenes.Profile} />
         <Route path={routes.auth.login} component={scenes.auth.Login} />
         // ...
         <Route path={routes.messages.unread} component={scenes.messages.Unread} />
         <Route path={routes.messages.detail.show} component={scenes.messages.Detail} />
      </Switch>
   )
}

Routes with parameters can be formatted using reverse function:

// Navigation.js
import React from 'react'
import { Link } from 'react-router'
import { reverse } from 'named-urls'

function Navigation({ messages }) {
   return (
      <ul>
         <li><Link to={`${routes.profile}`}>Profile</Link></li>
         // ...
         // Use reverse to replace params in route pattern with values
         {messages.map(message =>
            <li key={message.id}>
               <Link to={reverse(`${routes.messages.detail.show}`, { messageId: message.id })}>
                  Profile
               </Link>
            </li>
         )}
      </ul>
   )
}

Ending slash

Patterns ending with slash are always reversed to URL with ending slash and vice versa: Paterns without ending slash are always reserved to URL without endlish slash:

// pattern with ending slash
reverse('pattern/:optional?', { optional: 42 }) // pattern/42
reverse('pattern/:optional?') // pattern

// pattern without ending slash
reverse('pattern/:optional?/', { optional: 42 }) // pattern/42/
reverse('pattern/:optional?/') // pattern/

Migrating from v1.x.x to v2.x.x

For better compatibility with React Router, v2 uses path-to-regexp to resolve URLs. This means some of your routes may break when you upgrade.

reverse

-reverse('pattern/page:param?', {})
+reverse('pattern/(page:param)?', {})

reverseForce

-reverseForce('pattern/page:param?', {})
+reverseForce('pattern/(page:param)?', {})

To get a full overview of all accepted patterns, consult the path-to-regexp documentation.

Some tricks

Using an "include" route

If you define a route as an include, calling it directly will return you a function. To by-pass that, you have a solution to create an empty route inside, let's call it self:

// routes.js
import { include } from 'named-urls'

export default {
   messages: include('/messages', {
      self: '',

      detail: include(':messageId/', {
         show: '',
         edit: 'edit/',
         comments: 'comments/',
      })
   })
}

so you'll be able to do:

<Route path={routes.messages.self} component={Messages} />

A way to not define a useless route is to use the string way of a route like that:

// routes.js
import { include } from 'named-urls'

export default {
   messages: include('/messages', {
      detail: include(':messageId/', {
         edit: 'edit/',
         comments: 'comments/',
      })
   })
}
<Route path={`${routes.messages}`} component={Messages} />

// OR

<Route path={String(routes.messages)} component={Messages} />

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].