Skip to content

Instantly share code, notes, and snippets.

@petehouston
Forked from teaualune/_README.md
Created November 12, 2016 18:20
Show Gist options
  • Save petehouston/2de291736daccf1c8f7cb2b195c85081 to your computer and use it in GitHub Desktop.
Save petehouston/2de291736daccf1c8f7cb2b195c85081 to your computer and use it in GitHub Desktop.
An alternative routing example for React.js

This is a small example to build a simple routing solution for React.js instead of using the popular React Router.

It utilizes great libraries e.g. history and universal-router which are React-independent.

The example includes:

  • A singleton history object for URL navigation
  • A Router component to route different child components
  • A Link component that acts as those in React Router or in React Static Boilerplate
  • An example component App to demostrate their usages

The example is inspired mostly by You Might not need React Router.

External dependencies are listed as follows:

  • react: version 15.3.0
  • history: version 4.4.0
  • universal-router: version 2.0.0

Codes include the latest ES6/ES7 syntax e.g. function bind operator (::) and async/await.

import React from 'react';
import Router from './router';
import Link from './link';
export default function App() {
return (<div>
<header>Header</header>
<ul className="menu">
<li><Link href="/">Home</Link></li>
<li><Link href="/about">About</Link></li>
</ul>
<Router routes={[{
path: '/',
action: () => (<h1>Home</h1>)
}, {
path: '/about',
action: () => (<h1>About</h1>)
}]} />
<footer>Footer</footer>
</div>);
}
import createHistory from 'history/createBrowserHistory';
export default createHistory();
import React, { Component, PropTypes } from 'react';
import { resolve } from 'universal-router';
import history from './history';
export default class Router extends Component {
static propTypes = {
routes: PropTypes.oneOfType([
PropTypes.object,
PropTypes.array
]).isRequired
};
constructor(props) {
super(props);
this.state = {
child: null
};
}
componentWillMount() {
this.unlisten = history.listen(::this.onHistoryChanged);
this.onHistoryChanged(history.location);
}
componentWillUnmount() {
this.unlisten();
}
render() {
return this.state.child;
}
async onHistoryChanged(location) {
const child = await resolve(this.props.routes, {
path: location.pathname
});
this.setState({ child });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment