ReactJS Router has been broken into three bundles: react router, react router dom, and react router native.
You ought to never need to introduce react router straight forwardly. That bundle gives the center steering parts and capacities for React Router applications. The other two give condition particular (program and react native) segments, yet they both additionally re-trade all of react router’s fares.
We are building a site (something that will be kept running in programs), so we will introduce react router dom.
sudo npm install —? save react-router-dom
Configure the .babelrc file in the root of the project.
sudo touch .babelrc //Create a file
sudo nano .babelrc
Add the following code in .babelrc file
{
“presets”: [“es2015”, “react”]
}
Also Read:- How the Internet of Things relates to Artificial Intelligence
Create a file as index.html in a root directory and the following code -
sudo touch index.html //Create a file
sudo nano index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React Router Tutorial</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div id = "app"></div>
<script type = "text/javascript" src = "index.js"></script>
</body>
</html>
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;
Router
When beginning another undertaking, you have to figure out which sort of router to utilize. For program based undertakings, there are <BrowserRouter> and <HashRouter> parts. 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), while the <HashRouter> ought to be utilized for static sites (where the server can just react to demands for documents that it thinks about).
What you pick in 2018 : ReactJS vs AngularJS vs VueJS
Generally it is desirable over utilize a <BrowserRouter>, yet in the event that your site will be facilitated on a server that lone serves static documents, at that point the <HashRouter> is a decent arrangement.
Router segments just hope to get a solitary kid component. To work inside this constraint, it is valuable to make a <App> segment that renders whatever is left of your application. Isolating your application from the switch is likewise helpful for server rendering since you can re-utilize the <App> on the server while changing the switch to a <BrowserRouter>.
To configure 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'));
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">Welcome to React Router Tutorial</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;
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 pathname, you should utilize a <Route> component.
Also Read:- What you pick in 2018 : ReactJS vs AngularJS vs VueJS
Path
A <Route> expects a way prop, which is a string that portrays the pathname that the course matches?—?for illustration, <Route path=’/program’/> should coordinate a pathname that starts with/list. At the point when the present area’s pathname is coordinated by the way, the course will render a React component. At the point when the way does not coordinate, the course won’t render anything.
Uploading files with ReactJS and NodeJS
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 pathname. 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 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;
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;
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.
Also Read:- List of Top Mobile Apps Develop In React Native
Connect history api fallback
Single Page Applications (SPA) commonly just use one record document that is open by internet browsers: typically index.html. Route in the application is then regularly dealt with utilizing JavaScript with the assistance of the HTML5 History API. This outcomes in issues when the client hits the invigorate catch or is straightforwardly getting to a page other than the greeting page, e.g. /help or/help/online as the web server sidesteps the record document to find the record at this area. As your application is a SPA, the web server will come up short endeavoring to recover the document and restore a 404?—?Not Found message to the client.
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)
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”
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.
When You click login you will see the following output.