Routing in ReactJS

27 / Jul / 2015 by Dhiraj Sharma 0 comments

React-Router

In this blog we will talk about react-router. Routing is a dire need in SPA(Single page applications), in which we load partial content without asking the server for a complete webpage. React is no different in terms of loading only what is required. Routing programmatically presents specific content to users based on the URL that they are visiting. But, as we add more and more logic to an app, it grows very complex and soon become difficult to manage. Dividing it in components and using routing to load different components, helps in logically bifurcating  the app and making it more manageable.

 

Configuration

bower install react
bower install react-router
Or if you are not using bower, use the following CDN links:

https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.min.js


https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js


https://cdnjs.cloudflare.com/ajax/libs/react-router/0.13.3/ReactRouter.min.js

 

Setting up your page

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<script src="https://fb.me/JSXTransformer-0.13.2.js"/>
<script src="https://fb.me/react-with-addons-0.13.2.min.js"/>
<script src="bower_components/react-router/build/global/ReactRouter.min.js"/>
<script type="text/jsx" src="router.js"/>
<body>
  <div id="container"></div>
</body>
</html>

 

Basic example

(function (React, ReactRouter) {
    var Link = ReactRouter.Link,
        Route = ReactRouter.Route,
        RouteHandler = ReactRouter.RouteHandler;
    // List of Components
    var Parent = React.createClass({
        render: function () {
            return (
                <div>
                    <h2>This is the World.</h2>
                    <ul>
                        <li>
                            <Link to='india'>India </Link>
                        </li>
                        <li>
                            <Link to='usa'>USA</Link>
                        </li>
                    </ul>
                    <RouteHandler/>
                </div>
            );
        }
    });

    var India = React.createClass({
        render: function () {
            return (
                <div>
                India is a vast South Asian country with diverse terrain – from Himalayan peaks to Indian Ocean coastline – and history reaching back 5 millennia.
                In the north, Mughal Empire landmarks include Delhi’s Red Fort complex, massive Jama Masjid mosque and Agra’s iconic Taj Mahal mausoleum.
                    <RouteHandler/>
                </div>
            );
        }
    });
    var USA = React.createClass({
        render: function () {
            return (
                <div>
                The Americas, or America are the combined continental landmasses of North America and South America.
                Along with their associated islands, they cover 8.3% of the Earth's total surface area.
                    <RouteHandler/>
                </div>
            );
        }
    });

// Routing Information goes here
    var container = document.getElementById('container');
    var Routes = (
        <Route  name="parent" path="/" handler={Parent}>
            <Route name="india" path="/country/india" handler={India}/>
            <Route name="usa" path="/country/usa" handler={USA} />
        </Route>
    );
    ReactRouter.run(Routes, function (Handler) {
        React.render(<Handler/>, container);
    });
}(window.React, window.ReactRouter));

Link:  Creates an anchor tag that links to a route in the application. Also gets the active class automatically when the route matches. If you change the path of your route, you don’t have to change your links.


  <Link to='india' params={{"name": "India"}}>India </Link>

 //to:The name of the route to link to, or a full URL.
 //params: This props is used for passing parameter into url
 //query: It is used for passing parameter as query string into url

 

Route: It map routes to your application’s screen hierarchy.

 <Route  name="parent" path="/" handler={Parent}>
        <Route name="india" path="/country/india" handler={India}/>
         <Route name="usa" path="/country/usa" handler={USA} />
 </Route>

run(): It runs your routes, matching them against a location, and then calls back with the next state for you to render.

ReactRouter.run(Routes, function (Handler) {
        React.render(<Handler/>,null);
    });

RouteHandler: Component that renders the active child route handler of a parent route handler component. Any time you have nested routes you need to render a RouteHandler to get the UI to nest.

 

Passing parameters to Routes

<div>
   <Link to='india' params:{name:"India"}>India </Link>
  //Passing parameter in query string
   <Link to='india' query:{name:"India"}>India </Link>
</div>

//Route is defined as
 <Route name="india" path="/country/:name" handler={India}/>

You can try it out yourself on JSFiddle react-routerDemo .

To learn more about react-router visit react-router

I’d love to get your feedback !!

FOUND THIS USEFUL? SHARE IT

Leave a comment -