GithubHelp home page GithubHelp logo

react-router-named-routes's Introduction

react-router-named-routes

Build Status

This package provides support for named routes for React-Router 1, 2, 3, 4, and 5.

The support for named routes was once part of a core, but got removed at some point:

remix-run/react-router#1840 (comment)

Installation

npm install react-router-named-routes

React-router 4.0+

React-router v4 changed the game and we no longer have a single config file with all <Route/> components inside. Because of that we cannot map all routing patterns to resolve them based on their name. You will have to express all your routes using constants, like this:

routes.js:

export const USER_SHOW = '/user/:id'

and then import it whenever you need to use named routes:

import { USER_SHOW } from 'routes';
import { formatRoute } from 'react-router-named-routes';
<Route path={USER_SHOW} />
<Link to={formatRoute(USER_SHOW, {id: 1})} />
<Link to={{ pathname: formatRoute(USER_SHOW, {id: 1}) }} />

Additional benefit of this approach is that you get all the juice of static analysis if you use tools like flow or typescript.

(thanks to @Sawtaytoes for an idea)

React-router 3.0

Use <Link /> component provided by this package instead of the one provided by react-router. This requires some refactoring but not that much:

  1. Define all your routes in a single module. You probably do it like this anyway.
  2. Use this package before you render() anything:
var routes = require("myproject/routes");
var {Link, NamedURLResolver} = require("react-router-named-routes");
NamedURLResolver.mergeRouteTree(routes, "/");

<Route name="todo.edit" path="todo/:id/edit" component={TodoEditForm} />
<Link to="todo.edit" params={{id: 123}}>Edit</Link>
<Link to={{name: "todo.edit", search: "?param=1"}} params={{id: 123}}>Edit</Link>

React-router 2.0 and older

  1. Define all your routes in a single module. You probably do it like this anyway.
  2. Use this package before you render() anything:
var routes = require("myproject/routes");
var {FixNamedRoutesSupport} = require("react-router-named-routes");
FixNamedRoutesSupport(routes);

That's it, with three lines of code you saved yourself hours of refactoring! You may now use react-router just like in react-router 0.13:

<Route name="todo.edit" path="todo/:id/edit" component={TodoEditForm} />

<Link to="todo.edit" params={{id: 123}}>Edit</Link>

Caveats

This probably breaks the shiny new async routes feature introduced in ReactRouter 1.0.0. If you come straight from 0.13 you don't use it anyway.

Contributing

A pull request or an issue report is always welcome. If this package saved you some time, starring this repo is a nice way to say "thank you".

Advanced stuff and implementation details

Named Routes are resolved by a simple class called NamedURLResolverClass.

If you want some custom logic involved in resolving your named routes, or routes in general, you may extend the class NamedURLResolverClass from this package and replace the global resolver like this:

var {NamedURLResolverClass, setNamedURLResolver} = require("react-router-named-routes");
class CustomURLResolver extends NamedURLResolverClass {
  resolve(name, params) {
    // ...do some fancy stuff
  }
}
setNamedURLResolver(new CustomURLResolver());

Also, a <Link /> component will accept a resolver property if you don't want to use a default one for any reason:

<Link resolver={new CustomURLResolver()} />

License

New BSD and MIT.

react-router-named-routes's People

Contributors

adamziel avatar alecperkins avatar alex-mcleod avatar asrytis avatar elob avatar gorkalaucirica avatar jeron-diovis avatar just-paja avatar mpontus avatar sitch avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-router-named-routes's Issues

Does not resolve optional parameters in react router 4

Working with React Router 4 I found this feature is missing.

Input:

import {formatRoute} from 'react-router-named-routes';

const SOME_ROUTE = '/some-route/:optional?';

formatRoute(SOME_ROUTE, {optional: 'some-value'})

Expected output: /some-route/some-value
Current output: /some-route/:optional?

Updating npm package

Looks like a change was made to the package.json in this repo but has not yet been published to npm. Specifically, the version dependency for react-router has been changed to ^2.0.0, which prevents errors when versions of react-router other than 2.0.0 are installed. Would you please update the npm package? Thank you!

Dependency maintenance warning

I'm getting the following warning while using yarn.

react-router-named-routes > create-react-class > fbjs > [email protected]: core-js@<2.6.5 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.

Another approach

Hey, thanks for making this, I know it helped a lot of people.

I've got a new repository that takes advantage of the API we opened up in React Router to allow extensions like this without monkey patching.

Let me know if this implementation interests you. If so I'd like to make you an owner, and if you'd prefer we can transfer it to your account. We can work on it together and release it under the same name you've already got. Thanks :)

https://github.com/ryanflorence/react-router-named-routes

Uncaught TypeError: Cannot read property 'props' of null

...
function extractPaths(route) {
    var prefix = arguments.length <= 1 || arguments[1] === undefined ? "" : arguments[1];
    // Here a problem
    if (!route.props) return;
...

Code:

// routes.jsx
...
let routes = (
    <Route component={App} path='/'>
        <Route component={AppBase}>
            <IndexRoute component={Dashboard.Dashboard}/>
            {dashboard}
            {news}
            {company}
            ...
        </Route>
        {auth}
        <Route path="*" component={NoMatch}/>
    </Route>
);

import FixNamedRoutesSupport from "react-router-named-routes";
FixNamedRoutesSupport(routes);

export default routes;

Help

Hi, first of all, sorry for this type of issue :) - I am looking for an experienced developer in PHP and AS to help my client from UK. Would you be interested? (salary would be ~18k+all taxation/month).

If not - sorry for bothering.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.