Git Product home page Git Product logo

hirouter's Introduction

Build Status codecov GetBadges Game

HiRouter

HiRouter is a React High Order Component for the famous React Router for a even better routing experience.

npm install react-hirouter --save

HiRouter is capable to create convenience navigation functions. The idea is to keep the urls centralized (on your routers configuration) and using functions like goToOrder({orderId:1001}) instead of pushing the URLs manually to the routers history (usually like this router.push('/order/1001') )

HiRouter creates the navigation functions automagically, with arguments and names according to the route patterns, i.e.

bats/:hardly/hit/:balls/crazy turns into goToBatsHitCrazy({hardly:value1, balls:value2})

Advantage:

  • Centralized route definitions (better maintainability)
  • More expressive navigation (always nice)
  • Comfort (good for our lazy souls)

Example

Example:

This is a typical routing tree for react-router. Once defined your routes, you simply pass the router as parameter to the HiRouter. Using Reacts context declaration enables you to access the created navigation functions.

const router = <Router history={history}>
    <Route path="/" component={App}>
        // IndexRoutes are considered also
        <IndexRoute component={App}/>
	    <Route path="product/:id" component={ProductListContainer}/>
	    // HiRouter also works recursively
	    <Route path="client/" component={ClientContainer}>
	        // in the next line we use an *alias* parameter for better naming
	        <Route path=":clientId/order" component={ClientOrderListContainer} alias="ClientOrderList" />	        
	        <Route path=":clientId/order/:orderId" component={ClientOrder} />	        
	        <Route path=":clientId/order/:orderId/status" component={ClientOrderStatus} />	        
	    </Route>
	    // optional path variables are supported, too
	    <Route path="pony/(:foo)" component="{PonyFooContainer}" />	    
</Router>

// use the High Order Component (HOC) HiRouter
render( <HiRouter router={router} />, document.getElementById('root') )

Inside ProductListContainer you can access convenient routing/navigation functions

class ProductListContainer extends React.Component {
	constructor(){
		super() 
	}
	
	handleSelectedProduct(id){
	    // here we can conveniently navigate to the specific component
	    // *without* knowing the underlying url.
	    // mind, that the functions accept an object where its property 
	    // names refers to variable names in the path pattern 
		context.nav.goToProduct({id:id});
		// also available are
		/*
		context.nav.goToIndex() // default		
		context.nav.goToClientOrderList({clientId: 100}) // from alias for customized naming
		context.nav.goToClientOrder({clientId: 100, orderId:1001}) // of course, multiple args!
		context.nav.goToClientOrderStatus({clientId: 100, orderId:1001})		
		context.nav.goToPony() // optional variables #1		
		context.nav.goToPony({foo:'bam'}) // optional variables #2		
		*/
	}
	
	render(){
		return <ProductList onSelectedProduct={handleSelectedProduct.bind(this)} />
	}
}

// IMPORTANT: declare the usage of hirouters navigation context.
ProductListContainer.contextTypes = {
  nav: React.PropTypes.object
};

Options

HiRouter allows some tweaking.

Currently, options for function naming but also for routing internals are available. Available options are:

  • prefix : changes the first naming part of the navigation function
  • defaultPath : changes the second naming part of IndexRoute functions
  • routingImpl: a function used for routing (usually, you won't use this)

The default options are:

options : {
    prefix : "goTo",
    defaultPath : "Index",
    routingImpl: (url) => { this.props.history.push(url); }
}

Suppose, we configure our HiRouter like this

const router = 
  <Router history={history}>
    <Route path="/" component={App}>
        // IndexRoutes are considered also
        <IndexRoute component={App}/>
	    <Route path="product/:id" component={ProductListContainer} alias="Schawarma"/>
  </Router>

const options = {
  prefix: "mazelTov",
  defaultPath: "TohuWaBohu"
}

render( <HiRouter router={router} options={options}/>, document.getElementById('root') );

then HiRouter creates the following navigation functions:

  • mazelTovTohuWaBohu()
  • mazelTovSchawarma({id:'bla'})

Routing Implementation Function

The default routing function can be exchanged by a customized routing function, for whatever reasons. Its current default implementation simply pushes the url to the react-routers history - So, no rocket-science here.

function defaultRoutingImpl(url){
	// 'this' is the react-router instance passed as HiRouters *router* property
	this.props.history.push(url);
}

hirouter's People

Contributors

ohager avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

hirouter's Issues

Handle IndexRoute

Should be nice if IndexRoute can be handled, i.e. creating special goToIndex() function. Mind, that IndexRoute has a related parent Route

Consider special route patterns

Currently, only URL variables (i.e. path/:id) are parsed. See, how to treat more advanced patterns, like path/(:id), or /**/*.jpg

Compatibility Builds

Err, I wanted to use HiRouter in one of our projects, but got

events.js:141 throw er; // Unhandled 'error' event ^ SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'

Seems, that I need to babel the guy first. Thought it'd be babel'd by our build chain. Need to solve this. This way it's not usable ๐ŸŽฑ

ES5 support

In a current project we'd problems with IE11 due to Object.assign and string interpolation. While Object.assign can be resolved with a simple shim, the string interpolation feature is a bit more difficult to resolve. It is used inside the dynamic function creation (createMountPathFunction in createRouteFunction.js).

Page Transition not triggering

Under certain circumstances the transition does not trigger or stucks. I experience this mostly with Flux. A working solution seems to set the following routingImpl option.

const hiRouterOptions = {
		routingImpl: function(url){ setTimeout( () => this.props.history.push(url), 0 ); }
	};

ReactDOM.render(<HiRouter router={Router} options = {hiRouterOptions} />, document.getElementById('app-container'));

This kind of implementation should be default!

Get rid of require('react-hirouter').HiRouter

For some reasons the ES6,CJS build creates exports.default=HiRouter (in hirouter.js), which makes imports in React projects not that intuitive as I'd like to have. Instead of export default HiRouter I use an explicit export export {HiRouter}. This way, imports work like this const HiRouter = require('react-hirouter').HiRouter.

Ideally, it should be const HiRouter = require('react-hirouter')

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.