days
0
-10
-7
hours
-2
-1
minutes
0
-1
seconds
-5
-5
This makes building single page applications even easier

Build React.js routing using History API Fallback

Ashish Goyal
React
© Shutterstock / Thongchai Kitiyanantawong

Looking to use React to build single page applications? Sometimes, routing can be dfficult. In this article, Ashish Goyal explores how developers can use the History API fallback to create routes for their React apps and webpages.

In computing, React.js is an open source JavaScript library for creating User Interface (UI) specially for single page applications. It is developed and maintain by Facebook and it used for maintaining view layer for web and mobile applications.

React’s Router is defined in three bundles:

You’ll likely never need to present React Switch straightforwardly. That package gives the inside controlling parts and capacities with regards to React Router applications. The other two give condition specific (program and React Native) portions, yet they both also re-exchange all React Switch’s passages.

Here, we are building a site. Since this site is something that will be continued running in projects, so we will present how a developer would use this with React Router DOM.

Install React Router DOM

npm install — save react-router-dom 

Configure the .babelrc file in the root of the project.

touch .babelrc //Create a file

nano .babelrc //Edit a file 

Add the following code in .babelrc file

{
“presets”: [“es2015”, “react”]
} 

Index.html

Create a file as index.html in a root directory and use the following code:

touch index.html //Create a file

nano index.html //Edit a file

<!DOCTYPE >
<html lang = "en">
   <head>
      <meta charset = "UTF-8">
      <title>Build ReactJS Routing Using History API Fallback</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
	  <link rel="stylesheet" href="css/bootstrap.min.css">
	  <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22js%2Fjquery.min.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
	  <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22js%2Fbootstrap.min.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
   </head>
   <body>
      
<div id = "app"></div>

      <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%20%3D%20%22text%2Fjavascript%22%20src%20%3D%20%22index.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
   </body>
</html> 

SEE ALSO: New users pick Vue over React, report shows

Configuring webpack.config.js file

If you need to configure webpack.config.js file, add the following code in webpack.config.js.

var config = {
   entry: './main.js',
   output: {
      path:'/',
      filename: 'index.js',
   },
   devServer: {
      inline: true,
      port: 8545
   },
   module: {
      loaders: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
               presets: ['es2015', 'react']
            }
         }
      ]
   }
}

module.exports = config; 

SEE ALSO: Detect performance bottlenecks in your apps with React Profiler

Router

When beginning another undertaking, you have to figure out which sort of router to utilize. For program-based undertakings, there are BrowserRouter and parts HashRouter. The BrowserRouter ought to be utilized when you have a server that will deal with dynamic solicitations (knows how to react to any conceivable URI). The HashRouter should be used for static destinations (where the server can simply react to requests for records that it ponders).

By and large it is attractive over use a BrowserRouter, yet if your site will be encouraged on a server that solitary serves static records, by then the HashRouter is a fair game plan.

Router portions simply would like to get a lone child part. To work inside this limitation, it is profitable to make an section that renders whatever is left of your application. Confining your application from the switch is similarly useful for server rendering since you can re-use the on the server while changing the change to a BrowserRouter.

Configuring the Main.js file

To configure the Main.js file, add the following code in Main.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App/>, document.getElementById('app')); 

Configuring the App.js file

To configure App.js file, add the following code in App.js:

import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Home from './Home';
import login from './login';

class App extends Component {
   render() {
      return (
         <Router>
            
<div className="container-fluid">
               
<h2 className="text-center">Build ReactJS Routing Using History API Fallback</h2>

               
<nav className="navbar navbar-inverse">
                 
<ul className="nav navbar-nav">
                   
<li><Link to={'/'}>Home</Link></li>

                   
<li><Link to={'/login'}>Login</Link></li>

                 </ul>

               </nav>

               
<hr />


               <Switch>
                  <Route exact path='/' component={Home} />
                  <Route exact path='/login' component={login} />
               </Switch>
            </div>

         </Router>
      );
   }
}

export default App; 

SEE ALSO: Top 5 IDEs and text editors for React

Routes

The Route segment is the principle building square of React router. Anyplace that you need to just render content in light of the area’s path name, you should utilize a Route component.

Path

A Route expects a way prop, which is a string that portrays the path name that the course matches. For illustration, Route path=’/program’/ should facilitate a path name that begins with/list. Exactly when the present zone’s path name is composed coincidentally, the course will render a React part. Exactly when the way does not organize, the course won’t render anything.

Matching paths

React Router utilizes the way to-regexp bundle to decide whether a course component’s way prop coordinates the present area. It incorporates the way string into a normal articulation, which will be coordinated against the area’s path name. way strings have further developed designing choices than will be secured here. You can read about them in the way to-regexp documentation.

Create Components

To configure the Home.js file, add the following code in Home.js:

import React, { Component } from 'react';

class Home extends Component {
   render() {
      return (
         
<div>
            
<div className="jumbotron">
			  
<div className="container text-center">
			    
<h1>My Home</h1>

      
			  </div>

            </div>

         </div>

      );
   }
}

export default Home; 

SEE ALSO: A developer’s introduction to React

Configuring a Login.js file

To configure Login.js file, add the following code in Login.js:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Login extends Component {
	render() {
		return (
			
<div>
			    
<h2 className="text-center">Login</h2>

			    
<form action="">
			        
<div class="form-group">
			            <label for="email">Email address:</label>
			            <input type="email" class="form-control" id="email" />
			        </div>

			        
<div class="form-group">
			            <label for="pwd">Password:</label>
			            <input type="password" class="form-control" id="pwd" />
			        </div>

			        <button type="submit" class="btn btn-default">Submit</button>
			    </form>

			</div>

			);
		}
} 

export default Login; 

SEE ALSO: Vue.js vs React poll results: Vue.js ready to slay its competition

History

Every router makes a history question, which it uses to monitor the current location and re-render the site at whatever point that progressions. Alternate segments gave by React Router depend on having that history protest accessible through React’s unique situation, so they should be rendered as relatives of a router part. A React Router segment that does not have a router as one of its progenitors will neglect to work.

Connect history API fallback

Single Page Applications (SPA) generally simply utilize one record report that is open by web programs: commonly index.html. Course in the application is then frequently managed using JavaScript with the help of the HTML5 History API. This results in issues when the customer hits the empower get or is direct getting to a page other than the welcome page, e.g. /help or/help/online as the web server evades the record archive to discover the record at this zone. As your application is a SPA, the web server will miss the mark attempting to recoup the report and reestablish a 404 — Not Found message to the customer and compare of ReactJs vs AngularJs (https://xtreemsolution.com/blog/reactjs-vs-angularjs)

This tiny middleware addresses some of the issues. Specifically, it will change the requested location to the index you specify (default being /index.html) whenever there is a request which fulfills the following criteria:

  • The request is a GET request,
  • which accepts text/html,
  • is not a direct file request, i.e. the requested path does not contain a . (DOT) character and
  • does not match a pattern provided in options.rewrites (see options below).

Install History API fallback

We will install npm install — save connect-history-api-fallback.

Open the package.json and delete start: webpack-dev-server — hot inside scripts object. We are deleting this line since we will not do any testing in this tutorial. Let’s add the start command instead.

“start”: “webpack-dev-server — hot –history-api-fallback”

SEE ALSO: Companies are looking for React, machine learning, and Go

Running the server

The setup is complete, and we can start the server by running the following command.

npm start 

It will show the port we need to open in the browser. In our case, it is http://localhost:8545/. After we open it, we will see the following output.

React

When you click login, you will see the following output.

react

Author

Ashish Goyal

Ashish Goyal is a Digital Marketing Analyst for a well-known mobile application development company, active since 2008 with professional’s developers. Hire Mobile app developer form Xtreem Solution He loves to share his technology research and knowledge by writing blog or article. as a digital marketing analyst his aim to build leadership to growing a strong and environmentally sound IT Enterprise. You can connect with him on Twitter and LinkedIn.