Code Monkey home page Code Monkey logo

redux-first-router's Introduction

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

Version 2 released!

During the development of Rudy, a few versions were released under different names and npm tags. All of these plus several PRs have been combined to a stable, up-to-date and mostly compatible version which will be supported long-term. (See the migration instructions for version 2.)

Feature development efforts and the next version Rudy will be moved to a different repo in our Respond framework organization.

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.

Minimal example

// 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, thunk } = 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, thunk }
}
// 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 }

Recipes for...

Missing examples for your use-case? PRs are very welcome! Topics waiting to be added include:

  • Dispatching thunks on route changes
  • 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.

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).

More from FaceySpacey in Reactlandia

Reactlandia chat lobby

redux-first-router's People

Contributors

faceyspacey avatar scriptedalchemy avatar hedgepigdaniel avatar iansinnott avatar greenkeeper[bot] avatar sdougbrown avatar cdoublev avatar sergio-toro avatar guillaumecisco avatar mungojam avatar toerndev avatar chapati23 avatar miriam-z avatar mkamakura avatar re6exp avatar bobgy avatar chrisblossom avatar cthierer avatar erikmswan avatar ixje avatar geirsagberg avatar gouegd avatar shibe97 avatar maksimdegtyarev avatar mpontus avatar mrloh avatar nilos avatar valbrand avatar magicien avatar

Watchers

James Cloos avatar Joe Theis avatar

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.