Last active
September 25, 2016 05:48
-
-
Save tingwei628/7da6e11992197605891caee1104d05b0 to your computer and use it in GitHub Desktop.
Handle routes without React-Router
This file contains hidden or 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
// babel-core 6.x | |
import 'babel-polyfill'; | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
import createHistory from 'history/createBrowserHistory'; | |
import pathToRegexp from 'path-to-regexp'; | |
/* | |
your route setting here | |
*/ | |
const routeSetting = [ | |
{ | |
"path": "/", | |
"page": "./App.js" | |
}, | |
{ | |
"path": "about", // route | |
"page": "./containers/AboutPage/index.js" // file path | |
}, | |
]; | |
function resolve(currentLocation) { | |
let route = ''; | |
let regex = ''; | |
let page = ''; | |
let matchResult = null; | |
for (let i = 0, len = routeSetting.length; i < len; i++) { | |
route = routeSetting[i].path; | |
page = routeSetting[i].page; | |
regex = pathToRegexp(route); | |
matchResult = regex.exec(currentLocation); | |
if (matchResult !== null) { | |
break; | |
} | |
} | |
return { | |
matchResult, | |
page, | |
}; | |
} | |
function renderComponent(matchParams, callback) { | |
require.ensure([], (require) => { | |
const Component = require(matchParams.page).default; | |
ReactDOM.render(<Component />, document.getElementById('root')); | |
}); | |
} | |
const history = createHistory({ | |
basename: '/', | |
forceRefresh: false, | |
getUserConfirmation: (message, callback) => callback(window.confirm(message)) | |
}); | |
const pathname = history.location.pathname; // get current location | |
const match = resolve(pathname); // resolve route | |
renderComponent(match, null); // render components |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment