Author avatar

Gaurav Singhal

How to Use Backbone Router and React States

Gaurav Singhal

  • Apr 11, 2020
  • 8 Min read
  • 2,337 Views
  • Apr 11, 2020
  • 8 Min read
  • 2,337 Views
Web Development
Front End Web Development
Client-side Framework
React

Introduction

BackboneJS is primarily a JavaScript MVC framework, whereas React identifies itself as a JavaScript UI library. BackboneJS provides organized structure to your codebase and definitive models that can communicate with data. Using React as a view library in BackboneJS will improve your application's performance as React uses the virtual DOM.

In this guide, you'll learn how to use React components with a Backbone router.

Problems with the Existing View in BackboneJS

Backbone view is the template model that takes care of the UI and layout. A backbone view is identical to a React components in terms of function, but the working and performance differs. There are some problems you should be aware of when it comes to using Backbone views. This guide won't solve these issues, but will offer an alternate method using React components.

Non-reusable Views

Backbone views are much more challenging to reuse than React components. They sometimes become unhelpful and usually rely on rendering engines like Underscore or Mustache, which may restrict functionality.

Updating the DOM Is Tough

A typical pattern in BackboneJS is to listen to a variety of DOM events (click, change, etc.) and when triggered, manually refresh the DOM using jQuery to remove and append different elements.

Performance Problems

When it comes to performance, Backbone views cannot update DOM parts without re-rendering the whole DOM, which can be very costly. React overcomes this problem by using the virtual DOM and only updating the DOM parts that need a re-render.

Backbone Router

Backbone routers are used for routing your web application's URLs. Earlier, hash fragments (#page) were used to route the URLs, but with the introduction of the History API, it is now possible to route with standard URLs (/page).

Backbone routers don't exactly fit the traditional definition of an MVC router, although a Backbone router is still handy for any application that needs URL routing abilities. In a traditional MVC framework, the routing happens on the server side, whereas in Backbone the routing is handled in the client side by the browser.

Specified routers should always contain at least one route and a function to map the particular route to its corresponding view. In the example below, you can see how the routes are defined using Backbone.Router.

1import Backbone from "backbone";
2
3const Router = Backbone.Router.extend({
4  routes: {
5    foo: "foo",
6    bar: "bar"
7  },
8  foo: function () {
9    // action to map foo URL to the specific view
10  },
11  bar: function () {
12    // action to map bar URL to the specific view
13  }
14});
15
16new Router();
js

The extend() method creates a custom route class. It defines action functions that are triggered when certain URL parts are matched and provide a routes hash that pairs routes to specific actions.

The routes object defines a key-value pair for the router, where the key is the URL fragment and the value is its route or action function.

You can also pass route params into your route action by defining a parameter part such as :param, which matches a single URL component between slashes. It can be made optional by wrapping it in parenthesis: (/:param).

1const Router = Backbone.Router.extend({
2  routes: {
3    "foo/:id": "foo"
4  },
5  foo: function (id) {
6    console.log("Route param : ", id);
7  }
8});
js

Once the router has been instantiated and all of the routes are set up properly, call Backbone.history.start() to begin watching URL change or hashchange events and dispatching route actions. To use a regular URL structure instead of hash URLs, you can pass the pushState option to the start() method Backbone.history.start({ pushState: true }).

Rendering React Component Inside Route Action

In this section, you'll learn how to render a React component from within the route action function.

Start fresh by defining a new Router class.

1import { Router, history } from "backbone";
2
3const AppRouter = Router.extend({
4  routes: {
5    "": "init",
6    "profile/:id": "profile",
7    "search/:term": "search"
8  },
9  init: () => {
10    console.log("This is the first page");
11  },
12  profile: id => {
13    console.log("This is the profile page", id);
14  },
15  search: term => {
16    console.log("The user is searching for " + term);
17  }
18});
19
20new AppRouter();
21
22history.start({ pushState: true });
js

If you see the console logs when you navigate to the URLs, that means the routing has been set up perfectly.

Next, create React components for each route action.

1import React from "react";
2
3const IndexPage = () => (
4  <div>
5    <h1>Hey, this is the Home Page.</h1>
6  </div>
7);
8
9const ProfilePage = props => (
10  <div>
11    <h1>Thanks for visiting the Profile Page</h1>
12    <h2>The Profile ID is {props.profileId}</h2>
13  </div>
14);
15
16const SearchPage = props => (
17  <div>
18    <h1>Searching for {props.searchTerm}...</h1>
19  </div>
20);
jsx

To render the component in a DOM element, use the ReactDOM.render() method, just as you would in any other React application. To try it out, render the <IndexPage /> component from the init() function.

1import ReactDOM from "react-dom";
2
3const rootElement = document.getElementById("root");
4
5routes: {
6  // ...
7}
8init: () => {
9  ReactDOM.render(<IndexPage />, rootElement);
10};
11//
jsx

Now, if you visit the index URL, you should see the contents of the <IndexPage /> component. Instead of calling ReactDOM.render() again and again, create a helper function to render a component.

Put it all together and pass on the route parameters as props to the respective page components.

1// ...
2const rootElement = document.getElementById("root");
3
4const renderView = View => ReactDOM.render(View, rootElement);
5
6const AppRouter = Router.extend({
7  routes: {
8    "": "init",
9    "profile/:id": "profile",
10    "search/:term": "search"
11  },
12  init: () => renderView(<IndexPage />),
13  profile: id => renderView(<ProfilePage profileId={id} />),
14  search: term => renderView(<SearchPage searchTerm={term} />)
15});
16
17// ...
jsx

Complete Source Code

Below you can find the complete code for your reference.

1import React from "react";
2import ReactDOM from "react-dom";
3import { Router, history } from "backbone";
4
5const rootElement = document.getElementById("root");
6
7const renderView = View => ReactDOM.render(View, rootElement);
8
9const IndexPage = () => (
10  <div>
11    <h1>Hey, this is the Home Page.</h1>
12  </div>
13);
14
15const ProfilePage = props => (
16  <div>
17    <h1>Thanks for visiting the Profile Page</h1>
18    <h2>The Profile ID is {props.profileId}</h2>
19  </div>
20);
21
22const SearchPage = props => (
23  <div>
24    <h1>Searching for {props.searchTerm}...</h1>
25  </div>
26);
27
28const AppRouter = Router.extend({
29  routes: {
30    "": "init",
31    "profile/:id": "profile",
32    "search/:term": "search"
33  },
34  init: () => renderView(<IndexPage />),
35  profile: id => renderView(<ProfilePage profileId={id} />),
36  search: term => renderView(<SearchPage searchTerm={term} />)
37});
38
39new AppRouter();
40
41history.start({ pushState: true });
jsx

Conclusion

Backbone routes are simply objects that can handle the incoming route value from the URL and invoke a specific action for that route.

An important takeaway from this guide is that you should be flexible in implementing two or more JavaScript stacks into your application codebase. Doing so will help you get a general idea of how different libraries work with each other and how you can overcome each of their disadvantages.