Code Monkey home page Code Monkey logo

react-router-util's Introduction

react-router-util

Useful components and utilities for working with React Router

Install

$ npm install react-router-util

Usage

import {ipcRenderer as ipc} from 'electron';
import React from 'react';
import {Route, Link} from 'react-router-dom';
import {history, BrowserRouter as Router, Debug} from 'react-router-util';

ipc.on('goto-about', () => {
	history.push('/about');
});

const App = () => (
	<Router>
		<>
			<Debug/>

			<ul>
				<li><Link to="/">Home</Link></li>
				<li><Link to="/about">About</Link></li>
			</ul>

			<hr/>

			<Route exact path="/" component={Home}/>
			<Route path="/about" component={About}/>
		</>
	</Router>
);

API

history

A history singleton that you can use in <Router history={history}> to access the history from outside the router. Can be useful for programmatically navigating to a route when used in combination with non-React code, like Electron IPC events, etc.

<BrowserRouter> and <StaticRouter>

Same as the official <BrowserRouter> and <StaticRouter>, but with history={history} set to the above history singleton, so you can just import the singleton to access the router history object from outside the router. This behavior can be overridden with <BrowserRouter history={yourOwnHistory}>.

<Debug/>

Unrendered React component that prints the props of the current route component to the console when not in production.

<CurrentRoute/>

React component that renders the pathname of the current route. For example: /dashboard.

<RouteWithProps/>

Like <Route/>, but passes additional props to the given component. The following props are passed to the route: path, component, exact, strict, location, sensitive, while the rest are passed to the component.

Before:

<Route path="/unicorn" render={props => <Unicorn {...props} foo={'cake'} bar/>}/>

After:

<Route path="/unicorn" component={Unicorn} foo={'cake'} bar/>

<AuthenticatedRoute/>

An authenticated version of <Route/>. You pass it an isAuthenticated prop with a boolean of whether it's authenticated. If it's true, it will render the given component or redirect to the given redirectTo path. If it's false, it will redirect to /login or loginPath if specified. You can specify redirectFromLoginTo to have it redirect somewhere from the loginPath when authenticated. It accepts all the props <Route/> accepts except for render. Additional props are passed to the component. You can also pass it children.

Before:

<Route path="/" exact render={props => (
	isLoggedIn ? <MainView {...props}/> : <Redirect to="/login"/>
)}/>

After:

<AuthenticatedRoute
	path="/"
	exact
	isAuthenticated={isLoggedIn}
	component={MainView}
/>

Another example:

<AuthenticatedRoute
	path="/admin"
	isAuthenticated={isLoggedIn}
	redirectTo="/admin/dashboard"
	loginPath="/admin/login"
/>

Yet another example:

<AuthenticatedRoute isAuthenticated={this.state.isLoggedIn} redirectFromLoginTo="/dashboard">
	<Switch>
		<RouteWithProps path="/login" component={Login} {...this.state}/>
		<RouteWithProps component={Main} {...this.state}/>
	</Switch>
</AuthenticatedRoute>

Example with nested routes:

<AuthenticatedRoute path="/dashboard/:nested" isAuthenticated={this.state.isLoggedIn}>
	<Switch>
		<RouteWithProps path="/information" component={Information} {...this.state}/>
		<RouteWithProps path="/contact" component={Contact} {...this.state}/>
	</Switch>
</AuthenticatedRoute>

When using nested routes, the :nested value must be specified in the outer route so that matchPath can map it to the correct nested route (/information and /contact in this case).

<ConditionalRoute/>

A conditional version of <Route/>. You pass it a conditional prop with a boolean. If it's truthy, either the given trueComponent will be rendered or it will redirect to trueRedirectTo. If it's falsy, either the given falseComponent will be rendered or it will redirect to trueRedirectTo. It accepts all the props <Route/> accepts except for render.

Before:

<Route path="/" exact render={() => (
	isLoggedIn ? <MainView/> : <Redirect to="/login"/>
)}/>

After:

<ConditionalRoute
	path="/"
	exact
	conditional={isLoggedIn}
	trueComponent={MainView}
	falseRedirectTo="/login"
/>

It's a little bit more verbose, but declarative FTW.

<BackLink>

Like <Link>, but navigates to the previous route in the history. Accepts any props <Link> supports except for to.

<ForwardLink>

Like <Link>, but navigates to the next route in the history. Accepts any props <Link> supports except for to.

Related

  • react-extras - Useful components and utilities for working with React

react-router-util's People

Contributors

agouil avatar antoniofpereir avatar rafaelfbs avatar richienb avatar ronnyhaase avatar sindresorhus 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  avatar  avatar

react-router-util's Issues

Testing with MemoryRouter

I'm trying to write Ava unit tests for a component using AuthenticatedRoute, but I don't think there is a way to get this to work with the MemoryRouter right now. Do you have any suggestions for workarounds?

Backwards navigation helpers

Issuehunt badges

Per https://twitter.com/sindresorhus/status/953743983678717955

We have these two helpers in our app which have been useful:

goBackTo(pathname)

Looks back in history to find which entry matches pathname, and then moves back to that entry. We implemented using MemoryRouter; depending on the limitations of BrowserRouter, it might but always be possible (I don't think BrowserRouter has an entries array on router.history). This is useful when you have routes in history that the user should not go back to, for example when going through a wizard or filling out a multi-step form.

clearHistoryAndPush(location)

Goes back history.length - 1 and then replaces the current route with the new location (where location is anything that can be passed to history.push). This can be useful when, for example, the user logs out of the app.

There is a $30.00 open bounty on this issue. Add more on Issuehunt.

Add more tests and prop-types

Issuehunt badges

I didn't feel it was worth all the boilerplate and setup just for 4 super simple exports that I've manually tested well, but tests should be added when more things are added.

Should use AVA.

This task also includes adding prop types and default prop values to the types.

Inspiration: https://github.com/ReactTraining/react-router/tree/master/packages/react-router-dom/modules/__tests__

There is a $40.00 open bounty on this issue. Add more on Issuehunt.

Cannot be used in server side rendering

Issuehunt badges

Because of createBrowserHistory which throw: Browser history needs a DOM.

One solution may be to return a memory router if the module is loaded in a non-dom environment.
(I'm not using this module for the history export but for the useful route components).


IssueHunt Summary

[
<
i
m
g

s
r
c

'
h
t
t
p
s
:
/
/
a
v
a
t
a
r
s
3
.
g
i
t
h
u
b
u
s
e
r
c
o
n
t
e
n
t
.
c
o
m
/
u
/
1
7
6
6
0
1
8
?
v

4
'

a
l
t

'
r
a
f
a
e
l
f
b
s
'

w
i
d
t
h

2
4

h
e
i
g
h
t

2
4

r
a
f
a
e
l
f
b
s
]
(
h
t
t
p
s
:
/
/
i
s
s
u
e
h
u
n
t
.
i
o
/
u
/
r
a
f
a
e
l
f
b
s
)

h
a
s

b
e
e
n

r
e
w
a
r
d
e
d
.

Backers (Total: $40.00)

Submitted pull Requests


Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

Make `<AuthenticatedRoute/>` work in nested routes

Issuehunt badges

See:

// TODO: `history.location.pathname` probably doesn't work with nested routes

I think we need to borrow https://github.com/ReactTraining/react-router/blob/67bcd88c8c00ee3164333c5981daa461b7f834ec/packages/react-router/modules/Route.js#L49-L70 and use this.state.match instead, but I haven't really looked into it thoroughly.


IssueHunt Summary

antoniofpereir antoniofpereir has been rewarded.

Backers (Total: $60.00)

Submitted pull Requests


Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

Custom history doesn't support basename

Issuehunt badges

Since the exported BrowserRouter creates its own history, without allowing for configuration from props, this library doesn't support using a basename. I will toy around with what this could look like and if I find a nice solution I'll open a PR


IssueHunt Summary

alexzherdev alexzherdev has been rewarded.

Backers (Total: $40.00)

Submitted pull Requests


Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

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.