React Router: Routing is the process of redirecting a user to another page based on user actions or requests. ReactJS router is mainly used for single-page web application development. React Router is used to define multiple routes in your application. When a user types a specific URL into their browser and the URL path matches the “route” in the router file, the user is redirected to that specific route.
React Router is a standard library system built on React and used to create routes in React applications using the React Router Package. Provides the data displayed on the web page to the browser’s synchronous URL. It preserves the default structure and behavior of the application and is mainly used for developing single-page web applications.
Need of React Router
React Router plays a key role in presenting multiple views in a single-page application. Without React Router, you wouldn’t be able to display multiple views in your React application. Most social media sites like Facebook and Instagram use React Router to render multiple views.
Note- In this chapter, we will learn how to set up routing for an app.
React Router Installation
A simple way to install the react-router is to run the following code snippet in the command prompt window.
C:\Users\username\Desktop\reactApp>npm install react-router
Create Component
In this step, we will create four components. The App component will be used as a tab menu. The other three components (Home), (About) and (Contact) are rendered once the route has changed.
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router'
class App extends React.Component {
render() {
return (
<div>
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
{this.props.children}
</div>
)
}
}
export default App;
class Home extends React.Component {
render() {
return (
<div>
<h1>Home...</h1>
</div>
)
}
}
export default Home;
class About extends React.Component {
render() {
return (
<div>
<h1>About...</h1>
</div>
)
}
}
export default About;
class Contact extends React.Component {
render() {
return (
<div>
<h1>Contact...</h1>
</div>
)
}
}
export default Contact;
Add a Router
Now, we will add routes to the app. Instead of rendering the App element like in the previous example, this time the Router will be rendered. We will also set components for each route.
main.js
ReactDOM.render((
<Router history = {browserHistory}>
<Route path = "/" component = {App}>
<IndexRoute component = {Home} />
<Route path = "home" component = {Home} />
<Route path = "about" component = {About} />
<Route path = "contact" component = {Contact} />
</Route>
</Router>
), document.getElementById('app'))
When the app is started, we will see three clickable links at the localhost that can be used to change the route.
Also, read | React Fragments and Its Usage with Examples