Understanding React Routing
Routing is defined as the ability to navigate to different parts of the application when the URL is entered or clicked on an element like button, link etc. React has a React Router library that can be used to extend your application by adding routing capabilities. It has three types. React-router which is the core library, react-router-dom is a library that can be used for web applications and react-router-native which can be used with react native in the mobile applications.
Installing react router
Create the startup react application by using create-react-app. To install react router run the command shown below.
npm i react-router-dom
Implementing react router
We will see how to implement react routing with the help of an example. In the application a single component called App.js is there. Let’s call it home page and create another components for routing.
Contact.js
import React, { Component } from 'react';
class Contact extends Component {
render() {
return <div>
<h4>Contact</h4>
<p>This is Contact page.</p>
</div>
}
}
export default Contact;
Create About.js
import React, { Component } from 'react';
class About extends Component {
render() {
return <div>
<h4>About</h4>
<p>This is About page.</p>
</div>
}
}
export default About;
App.js
import React, { Component } from 'react';
class App extends Component {
render() {
return <div>
<h4>Home</h4>
<p>This is Home page.</p>
</div>
}
}
export default App;
React router has four main components: BrowseRouter, Switch, Route, Link. These components helps to implement routing in our application.
BrowseRouter- It uses HTML5 history API to keep track of your UI and sync with URL.
Switch- It calls the first child that matches the location.
Route- Its duty is to render component UI when a location matches the route’s path.
Link- To manage navigation.
All the routing packages are updated in index.js as shown below.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { BrowserRouter, Switch, Route, Link } from 'react-router-dom'
import App from './App';
import About from './About';
import Contact from './Contact';
const routing = (
<BrowserRouter>
<div>
<h3>Clue Mediator</h3>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
<Switch>
<Route exact path="/" component={App} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</div>
</BrowserRouter>
)
ReactDOM.render(routing, document.getElementById('root'));
Comments
0 comments
Please Sign in or Create an account to Post Comments