Skip to content

Instantly share code, notes, and snippets.

@BenjaminVerble
Forked from HenrikJoreteg/README.md
Created December 29, 2015 00:50
Show Gist options
  • Save BenjaminVerble/ea693d134059d80a518a to your computer and use it in GitHub Desktop.
Save BenjaminVerble/ea693d134059d80a518a to your computer and use it in GitHub Desktop.
Minimalist routing in Redux
export const SET_URL = 'SET_URL'
/* global __IS_DEV__*/
import React from 'react'
import { createStore, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import FooApp from './foo-app'
import * as reducers from '../reducers'
import * as UrlActions from '../actions/url-actions'
export default class App {
render(data) {
let store = createStore(createStore(reducers))
if (typeof window !== 'undefined') {
window.addEventListener('popstate', () => {
store.dispatch(UrlActions.setUrl(window.location.pathname))
})
// grab last known URL from localStorage if in iOS standalone mode
const start = (navigator.standalone && localStorage.lastUrl) || window.location.pathname
store.dispatch(UrlActions.setUrl(start))
}
return (
<Provider store={store}>
{() => <FooApp />}
</Provider>
)
}
}
import React from 'react'
import { bindActionCreators } from 'redux'
import { Connector } from 'react-redux'
import InternalNav from 'react-internal-nav'
import AboutPage from '../components/about-page'
import DataPage from '../components/data-page'
import PersonDetail from '../components/person-detail'
import OverlayPage from './overlay-page'
import * as UrlActions from '../actions/url-actions'
export default class FooApp {
render() {
return (
<Connector>
{this.renderChild}
</Connector>
)
}
renderChild({ personData: {persons}, dispatch, url }) {
const actions = {
...bindActionCreators(UrlActions, dispatch)
}
let page
let style
if (url === '/') {
// render to URL as well
setQueryString({q: query})
} else if (url === '/about') {
page = (<AboutPage/>)
} else if (url === '/data') {
page = (<DataPage persons={persons}/>)
} else {
let match
persons.some(person => {
if (person.slug === url.slice(1)) {
match = person
return true
}
})
if (match) {
page = (<PersonDetail person={match} {...actions}/>)
} else {
page = (<h1>404</h1>)
}
}
if (page) {
page = (
<OverlayPage setUrl={actions.setUrl}>
{page}
</OverlayPage>
)
}
return (
<InternalNav onInternalNav={actions.setUrl}>
<header>
<nav role='navigation'>
<a href='/'>Example.com</a>
<span>
<a href="/data">Notes</a>
<a href="/about">About</a>
</span>
</nav>
</header>
{page}
</InternalNav>
)
}
}
import { SET_URL } from '../constants/action-types'
function pushState(url) {
if (url !== window.location.pathname) {
window.history.pushState({}, '', url)
}
}
export function setUrl(text) {
pushState(text)
return {
type: SET_URL,
text
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment