-
Notifications
You must be signed in to change notification settings - Fork 31
Using with React
Rick Carlino edited this page Jul 25, 2017
·
2 revisions
Rlite wasn't designed with React in mind, but that said, it can be made to play nice. Here's a sample file used in one of my projects (which uses Redux):
// react-rlite.js
'use strict'
import Rlite from 'rlite-router'
import React from 'react'
import {render, unmountComponentAtNode} from 'react-dom'
import {Provider} from 'react-redux'
export default function (store, rootEl) {
const router = Rlite()
const viewContainer = rootEl || document.querySelector('.react-container')
let started = false
// Renders the specified component, giving it the route's url parameters as
// well as invoking an optional "before action"
function renderRoute(urlParams, Component, beforeAction) {
store.dispatch({type: 'ROUTE_CHANGE', urlParams})
if (beforeAction) {
store.dispatch(beforeAction(store.getState(), urlParams))
}
const view = React.createElement(
Provider,
{store},
React.createElement(Component, {urlParams})
)
scrollTo(0, 0)
unmountComponentAtNode(viewContainer)
render(view, viewContainer)
}
// Hash-based routing
function processHash() {
const hash = location.hash || '#'
router.run(hash.slice(1))
}
return {
add (url, Component, beforeAction) {
router.add(url, ({params}) => renderRoute(params, Component, beforeAction))
return this
},
start () {
if (!started) {
started = true
window.addEventListener('hashchange', processHash)
processHash()
}
}
}
}
Given that definition of react-rlite
, it can be used like this:
// Import some components that you've written
import Home from './home'
import NewUser from './new-user'
import EditUser from './edit-user'
// Import the router object
import Router from 'react-rlite'
// Import some ajax helper or other, if you need to load stuff...
import ajax from 'ajax'
// Import your redux store or create it
import store from './store'
const router = Router(store)
// Register routes...
router.add('', Home)
router.add('users', Home)
router.add('users/new', NewUser, beforeNew)
router.add('users/:id', EditUser, beforeEdit)
// Start the router
router.start()
// The (optional) before functions take a state, and the rlite
// url parameters and return an action to dispatch via Redux.
function beforeNew(state) {
return {
user: { name: '', age: 0 },
type: 'NEW_USER'
}
}
// Here, we'll load some data from an API,
// using redux-thunk or something like it
function before(state, urlParams) {
return dispatch => ajax.fetch(`/api/users/${urlParams.id}`)
.then(user => dispatch({ TYPE: 'EDIT_USER', user }))
}