• Stars
    star
    1,568
  • Rank 29,726 (Top 0.6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🎖 seamless redux-first routing -- just dispatch actions

Redux-First Router

Think of your app in terms of states, not routes or components. Connect your components and just dispatch Flux Standard Actions!

Version Min Node Version: 6 Downloads Build Status

Motivation

To be able to use Redux as is while keeping the address bar in sync. To define paths as actions, and handle path params and query strings as action payloads.

The address bar and Redux actions should be bi-directionally mapped, including via the browser's back/forward buttons. Dispatch an action and the address bar updates. Change the address, and an action is dispatched.

In addition, here are some obstacles Redux-First Router seeks to avoid:

  • Rendering from state that doesn't come from Redux
  • Dealing with the added complexity from having state outside of Redux
  • Cluttering components with route-related code
  • Large API surface areas of frameworks like react-router and next.js
  • Routing frameworks getting in the way of optimizing animations (such as when animations coincide with component updates).
  • Having to do route changes differently in order to support server-side rendering.

Usage

Install

yarn add redux-first-router

(A minimal <Link> component exists in the separate package redux-first-router-link.)

Quickstart

// configureStore.js
import { applyMiddleware, combineReducers, compose, createStore } from 'redux'
import { connectRoutes } from 'redux-first-router'

import page from './pageReducer'

const routesMap = {
  HOME: '/',
  USER: '/user/:id'
}

export default function configureStore(preloadedState) {
  const { reducer, middleware, enhancer } = connectRoutes(routesMap)

  const rootReducer = combineReducers({ page, location: reducer })
  const middlewares = applyMiddleware(middleware)
  const enhancers = compose(enhancer, middlewares)

  const store = createStore(rootReducer, preloadedState, enhancers)

  return { store }
}
// pageReducer.js
import { NOT_FOUND } from 'redux-first-router'

const components = {
  HOME: 'Home',
  USER: 'User',
  [NOT_FOUND]: 'NotFound'
}

export default (state = 'HOME', action = {}) => components[action.type] || state
// App.js
import React from 'react'
import { connect } from 'react-redux'

// Contains 'Home', 'User' and 'NotFound'
import * as components from './components';

const App = ({ page }) => {
  const Component = components[page]
  return <Component />
}

const mapStateToProps = ({ page }) => ({ page })

export default connect(mapStateToProps)(App)
// components.js
import React from 'react'
import { connect } from 'react-redux'

const Home = () => <h3>Home</h3>

const User = ({ userId }) => <h3>{`User ${userId}`}</h3>
const mapStateToProps = ({ location }) => ({
  userId: location.payload.id
})
const ConnectedUser = connect(mapStateToProps)(User)

const NotFound = () => <h3>404</h3>

export { Home, ConnectedUser as User, NotFound }

Documentation

Basics

Flow Chart

Redux First Router Flow Chart

connectRoutes

connectRoutes is the primary "work" you will do to get Redux First Router going. It's all about creating and maintaining a pairing of action types and dynamic express style route paths. If you use our <Link /> component and pass an action as its href prop, you can change the URLs you use here any time without having to change your application code.

URL parsing

Besides the simple option of matching a literal path, all matching capabilities of the path-to-regexp package we use are now supported, except unnamed parameters.

Flux Standard Actions

One of the goals of Redux First Router is to NOT alter your actions and be 100% flux standard action-compliant. That allows for automatic support for packages such as redux-actions.

Location Reducer

The location reducer primarily maintains the state of the current pathname and action dispatched (type + payload). That's its core mission.

Link Component

A minimal link component exists in the separate package redux-first-router-link.

Query Strings

Queries can be dispatched by assigning a query object containing key/vals to an action, its payload object or its meta object.

React Native

Redux First Router has been thought up from the ground up with React Native (and server environments) in mind. They both make use of the history package's createMemoryHistory. In coordination, we are able to present you with a first-rate developer experience when it comes to URL-handling on native. We hope you come away feeling: "this is what I've been waiting for."

Advanced

addRoutes

Sometimes you may want to dynamically add routes to routesMap, for example so that you can codesplit routesMap. You can do this using the addRoutes function.

Blocking navigation

Sometimes you may want to block navigation away from the current route, for example to prompt the user to save their changes.

Scroll Restoration

Complete Scroll restoration and hash #links handling is addressed primarily by one of our companion packages: redux-first-router-restore-scroll (we like to save you the bytes sent to clients if you don't need it).

Server Side Rendering

Ok, this is the biggest example here, but given what it does, we think it's extremely concise and sensible.

Client-Only API

The following are features you should avoid unless you have a reason that makes sense to use them. These features revolve around the history package's API. They make the most sense in React Native--for things like back button handling.

Low-level API

Below are some additional methods we export. The target user is package authors. Application developers will rarely need this.

Version 2 Migration Steps

In earlier versions history was a peerDependency, this is no longer the case since version 2 has its own history management tool. This means that the arguments passed to connectRoutes(documentation) need to be changed.

Usage with redux-persist

You might run into a situation where you want to trigger a redirect as soon as possible in case some particular piece of state is or is not set. A possible use case could be persisting checkout state, e.g. checkoutSteps.step1Completed.

Prior Art

These packages attempt in similar ways to reconcile the browser history with redux actions and state.

Recipes

Help add more recipes for these use cases. PR's welcome!

Topics for things you can do with redux-first-router but need examples written:

  • Performing redirects bases on state and payload.
  • Use hash-based routes/history (see the migration instructions)
  • Restoring scroll position
  • Handling optional URL fragments and query strings
  • Route change pre- & post-processing
  • Code-splitting
  • Server-side rendering
  • Usage together with react-universal-component, babel-plugin-universal-import, webpack-flush-chunks.

Where is new feature development occuring?

Feature development efforts are occuring in the Respond framework Rudy repository.

Contributing

We use commitizen, run npm run cm to make commits. A command-line form will appear, requiring you answer a few questions to automatically produce a nicely formatted commit. Releases, semantic version numbers, tags, changelogs and publishing will automatically be handled based on these commits thanks to [semantic-release](https:/ /github.com/semantic-release/semantic-release).

Community And Related Projects

More Repositories

1

react-universal-component

🚀 The final answer to a React Universal Component: simultaneous SSR + Code Splitting
JavaScript
1,696
star
2

extract-css-chunks-webpack-plugin

Extract CSS from chunks into multiple stylesheets + HMR
JavaScript
691
star
3

webpack-flush-chunks

💩 server-to-client chunk discovery + transportation for Universal Rendering
JavaScript
355
star
4

universal-demo

DEMO: Webpack Flush Chunks + React Universal Component 3.0 🚀
JavaScript
230
star
5

tracker-react

No-Config reactive React Components with Meteor
JavaScript
126
star
6

redux-first-router-demo

Kick-Ass Universal RFR Demo That Answers Your SSR + Splitting Questions
JavaScript
125
star
7

babel-plugin-universal-import

🍾 universal(props => import(`./${props.page}`)) + dual css/js imports
JavaScript
114
star
8

redux-first-router-link

<Link /> + <NavLink /> that mirror react-router's + a few additional props
JavaScript
55
star
9

jest-storybook-facade

JavaScript
53
star
10

babel-plugin-dual-import

NOTE: now use babel-plugin-universal-import if you're using React Universal Component
JavaScript
50
star
11

require-universal-module

Universal-Rendering Module Loading Primitives
JavaScript
28
star
12

transition-group

What React CSS Transition Group is s'posed to be
JavaScript
25
star
13

respond-framework-docs-old

25
star
14

redux-first-router-boilerplate

JavaScript
23
star
15

flush-chunks-boilerplate

💩 A boilerplate showing how to achieve Universal Code-Splitting and Universal HMR with react-loadable, webpack-flush-chunks and extract-css-chunks-webpack-plugin
JavaScript
18
star
16

redux-first-router-restore-scroll

JavaScript
13
star
17

remixx

JavaScript
12
star
18

flush-chunks-boilerplate-babel-chunknames

babel boilerplate for Webpack Flush Chunks + React Universal Component + webpack's "magic comment" feature
JavaScript
10
star
19

travis-github-status

Set statuses on github from travis for jest, flow, + eslint
JavaScript
8
star
20

extract-css-chunk

JavaScript
7
star
21

jest-redux-snap

📸 reactive test helpers for redux and jest. snap everything!!!
JavaScript
7
star
22

redux-first-router-codesandbox

HOW TO USE: https://medium.com/faceyspacey/redux-first-router-lookin-sexy-on-code-sandbox-d9d9bea15053
JavaScript
6
star
23

react-native-20-screcorder-demo

JavaScript
6
star
24

redux-first-router-navigation

JavaScript
5
star
25

flush-chunks-boilerplate-webpack

universal webpack boilerplate for Webpack Flush Chunks + React Universal Component
JavaScript
5
star
26

rudy

JavaScript
5
star
27

blog-demo

JavaScript
3
star
28

redux-first-router-demo-codesandbox

JavaScript
3
star
29

redux-first-router-scroll-container

JavaScript
3
star
30

redux-first-router-navigation-boilerplate

JavaScript
3
star
31

nucleus

JavaScript
2
star
32

universal-react-vue-loader-demo

JavaScript
2
star
33

animated-transition-group

like <ReactTransitionGroup /> + callbacks, extras and child-specific customization
JavaScript
2
star
34

universal-render

2
star
35

ck

JavaScript
1
star
36

pure-redux-router

👶 Seamless Redux-First Routing
JavaScript
1
star
37

webpack-server-middleware

Hot updates Webpack bundles on the server
JavaScript
1
star
38

rudy-match-path

JavaScript
1
star
39

flush-chunks-boilerplate-babel

babel boilerplate for Webpack Flush Chunks + React Universal Component
JavaScript
1
star
40

redux-first-router-scroll-container-native

scroll restoration for React Native using Redux First Router
JavaScript
1
star
41

coastbeachwear

Web Store for Coast Beachwear Inc.
JavaScript
1
star
42

rfr-demo-mike

Created with CodeSandbox
JavaScript
1
star