Created
January 3, 2016 15:12
-
-
Save jamespantalones/1ca259aa650f8fa95a82 to your computer and use it in GitHub Desktop.
React universal routing demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// client | |
import router from 'path/to/isomorphic/router'; | |
import createLocation from 'history/lib/createLocation'; | |
import createBrowserHistory from 'history/lib/createBrowserHistory'; | |
const location = createLocation(document.location.pathname, document.location.search); | |
const history = createBrowserHistory(); | |
router(location, history) | |
.then((reactEl) => { | |
React.render(reactEl, dist); | |
}, (err) => { | |
throw err; | |
}) | |
// server | |
import routing from 'path/to/routing/middleware'; | |
// ... | |
app.use(routing) | |
// ... | |
// routing middleware | |
import React from 'react'; | |
import createLocation from 'history/lib/createLocation' | |
import createMemoryHistory from 'history/lib/createMemoryHistory'; | |
import router from 'path/to/isomorphic/router'; | |
export default function(req, res) { | |
let location = createLocation(req.url); | |
router(location, history, res, req) | |
.then((reactEl) => { | |
try { | |
let reactStr = React.renderToString(reactEl); | |
res.send(reactStr); | |
} catch (err) { | |
res.status(500).send({error: err.toString()}); | |
} | |
}, (err) => { | |
console.log('err', err); | |
res.status(500).send({error: err}); | |
}); | |
} | |
// router | |
import Promise from 'promise'; | |
import Router, {match, RoutingContext} from 'react-router'; | |
import routes from './routes.js'; | |
function getRootComponent(renderProps) { | |
let component = null; | |
if (__SERVER__) { | |
component = (<RoutingContext {...renderedProps}/>); | |
} else { | |
component = React.createElement(Router, renderedProps); | |
} | |
return component; | |
} | |
export default function (location, history, res, req) { | |
return new Promise((fullfill, reject) => { | |
match({routes, location, history}, (error, redirectLocation, renderProps) => { | |
if (!error) { | |
if (renderProps) { | |
renderProps.history = history; | |
} | |
fullfill(getRootComponent(renderProps)); | |
} else { | |
reject(error); | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment