This blog’s goal is to explain the Add Routing feature to React-App so we can move from one page to another page on click.
We will be building a single-page application website.
Here is the website action, no fancy styling, just a simple functional website.
We are building a single-page website that will be running in your browser, so we will install react-router-dom.
A simple way to install is to run the following command :
npm install --save react-router-dom
We have different types of Routers :
1) <BrowserRouter> use when you have Server or URL that handles the Dynamic request
2) <HashRouter> use for static website
For this project we are going to use <BrowserRouter>, we assume that the website will be backed by a dynamic server.
Add a router to App.js
This <App> component is wrapping the rest of our application.
Our application is defined as <App> so we will divide the app into two parts:
1) <Header> which will contain the navigator
2) <Content> where the rest of Content will be rendered on click of different components from the header
Adding routes in Content
Now we just need to render our <Switch> and <Route>s inside <Content> component, which will be in <content> which is a self-generated tag. You can use <Switch> component to group the <Route>s. <Switch> will iterate over the <Route>s and only render the first one that matches the current path name.
The pathnames that we want to match are:
1. / -for homepage
2. /technologies – for the working technologies
3. /services – for the services page
Note: The route for the home includes exact props. This states that the route should only match when the pathname matches the route’s path exactly.
Add Link to Header
Our application needs a way to navigate between the pages. React Router provides a <Link> component. On clicking a <Link>, URL content will be updated and the rendered content will change without reloading the page.
Now react routing will work properly.
Hope this blog will be useful for react developers.