Do you want to handle and render multiple components in React? If yes then this post is only for you. Yeah, I am talking about navigating from component to component. While navigating to components the page doesn’t refresh in React. Also, it needs to change the route dynamically. If you render the child components in a parent then it will be rendered one after one by default. So, what if you don’t want to render all components at the same time? Here, we will use React router to handle the components navigation and routing. Every time when you will navigate to another component, you can set the route for it. For managing routing, React uses the React Router DOM.
Also, on the basis of the route, you can set the component that you want to load. Even you can manage the redirection through the browser URL. In this React post, I will be giving you a brief overview of React Router DOM. To manage the react routes, we will use the React Router DOM.
React Router
React Router is a collection of navigational components that compose declaratively with your application. It allows changing the browser URL and keeps the components linked with the URL. Even it uses dynamic routing. React Router provides two different routing systems.
- Web – It is used in React JS web applications.
- Mobile – It is for a mobile application that is used by React Native.
Why React Router
We use React JS for the single-page application. React Router, allows us to build a single-page web application with navigation. It loads components without the page refreshing as the user navigates. React Router uses component structure to call components.
Prerequisites
I am sure your system is ready to create a React app. If not then you have to install the Node.js >= 10.
If you are an absolute beginner in React. And you have no idea about the installation then follow up on my previous post. I have already shared a post on how to start with a React app.
Now, let’s create a new app in React js.
Create React App For Implementing React Router
To create a new app in React, just open the terminal or command prompt and hit the below command.
npx create-react-app blog
The above command will start the installation of React js in the specified folder.
After creating the React app, you need to navigate to the folder and run it.
npm start
It will start
Before moving to the React routes implementation, I would like to install Bootstrap.
Create a Todo App in React Using Laravel 8 RESTful APIs
Install Bootstrap in React js
If you have no idea about the third party packages in React then go to the official website of npm js. You can install the third party available packages from here. So, I will search for the Bootstrap.
You can check the command for the installation. Now, you have to come back to your terminal and hit the below command.
npm i bootstrap
Here, I want to have the latest version of Bootstrap. Hence, I haven’t specified the version. If you want any specific version then you can put it up here.
It will take a couple of seconds to install the package inside your project.
You can check the installed package inside the project. You need to got to the package.json file.
React Login and Registration App Using Laravel 7 API
Import Bootstrap in React
Before using the Bootstrap classes in React JSX you need to import the CSS and JS. So, according to the React js file structure, we have the index.js file. Hence, you need to import it inside the index.js file. This will be the global, so we can use it in every component.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
// import bootstrap
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import '../node_modules/bootstrap/dist/js/bootstrap.min.js'
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
In this post, I will be creating navigation bar using the Boostrap 5. So, that you can have the better understanding of the React Routers and React Router Link. Because, through the navigation bar, we will have the multiple links and we can checkout everything here.
Hence, let’s create some components here.
Create a CRUD App in React.js Using Laravel 7 RESTful API
Create Components in React JS
For creating the navigation and the React Router, create the following components one by one. But, before that, create a folder with the name components inside the src folder.
- Header.js
- Home.js
- About.js
- Contact.js
src
|___ components
|__ Header.js
|__ Home.js
|__ About.js
|__ Contact.js
After creating the above components, firstly, create a navigation bar using Bootstrap 5. Hence, we will use the Header component for the navigation bar.
Create a Navigation Bar in React JS
Navigate to the Header component and let’s add the below snippet there. Here, I have created the class component.
import React from 'react';
export default class Header extends React.Component {
render() {
return (
<nav className="navbar navbar-expand-lg navbar-dark bg-dark sticky-top">
<div className="container">
<a href="#" className="navbar-brand">Programming Fields</a>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNavAltMarkup">
<ul className="navbar-nav ms-auto">
<li className="navbar-item">
<a href="#" className="nav-link" aria-current="page">Home</a>
</li>
<li className="navbar-item">
<a href="#" className="nav-link">About Us</a>
</li>
<li className="navbar-item">
<a href="#" className="nav-link">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
);
}
}
Create REST API in Laravel 8 Using JWT Authentication
Create Home, About, and Contact Component
In rest components put a just title to identify the component. Start from Home component.
import React, { Component } from 'react';
export default class Home extends Component {
render() {
return (
<h2 className="text-center">This is Home page</h2>
);
}
}
Secondly, do the same thing in the About component.
import React, { Component } from 'react';
export default class About extends Component {
render() {
return (
<h2 className="text-center">This is About page</h2>
);
}
}
Lastly, for the Contact component add the same title.
import React, { Component } from 'react';
export default class Contact extends Component {
render() {
return (
<h2 className="text-center">This is Contact page</h2>
);
}
}
I have added a simple heading with a title in the above components.
How to Create Github Login in Laravel 8 Using Socialite
Render Components in React JS
Firstly, import the Header component only inside the App component. So that it can be rendered to display the result.
import React, { Component } from 'react';
import Header from './components/Header';
class App extends Component {
render() {
return (
<Header/>
);
}
}
export default App;
Now, switch to the browser and check the result.
Here, the main issue occurs. How you will add the particular components with their respective navigation links? We have Home, About, and Contact components. Also, we have the navigation link for the same in the header.
If you try rendering the components respectively inside the App component, it will be rendered one after one. Let’s checkout the result by adding the below code.
import React, { Component } from 'react';
import Header from './components/Header';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';
class App extends Component {
render() {
return (
<>
<Header/>
<Home/>
<About/>
<Contact/>
</>
);
}
}
export default App;
Navigate back to the browser and see the result.
Here, you can achieve this using the React Routing concepts. React uses React Router DOM for managing the routes and components linking.
Hence, you need to install the package for it.
How to Create Login with Twitter in Laravel 8 Using Socialite
Install React Router DOM in React JS
To install the React Router DOM, you need to hit the below command. It will install the latest version.
npm i react-router-dom
Here, the React Router DOM is installed. Now, we can use it for implementing the React Routes.
Use of React Route
After installing the package, let’s come to the App.js component and import some components from react-router-dom
.
import { Route, BrowserRouter as Router } from 'react-router-dom';
Here, I have imported Route and BrowserRouter component.
- Here, the Route will be used to set the URL for a view. Also, it syncs the component with the specified URL.
- The BrowserRouter is aliased as Router. So, here if you have multiple Routes, then need to wrapped out inside the BrowserRouter. Here, we created the alias, hence, we can use the
<Router></Router>
component instead of<BrowserRouter></BrowserRouter>
.
import React, { Component } from 'react';
import Header from './components/Header';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';
import { Route, BrowserRouter as Router } from 'react-router-dom';
class App extends Component {
render() {
return (
<Router>
<Header/>
<Route path="/" component={ Home } />
<Route path="/about" component={ About } />
<Route path="/contact" component={ Contact } />
</Router>
);
}
}
export default App;
In the above code, I have set three routes and wrapped it inside the Router. Now, you can use these routes in the browser URL to load the components. Switch back to the browser and let’s checkout the result.
Get Result of Using React Route
We set the Home component in “/” route. So, when the app will load, it will render the Home component.
Now, change the route to /about
and you will have the Home
as well as About
component content.
But, this is not an actual result that we were expecting. We navigated to the /about route and it must show load only the About component. This is happening because of route expression doesn’t check strictly. So, it is treating “/” and “/about” as same. Similarly, it will be for the “/contact”.
So, we need to fix it by adding the attribute named exact
for the first “/” route.
import React, { Component } from 'react';
import Header from './components/Header';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';
import { Route, BrowserRouter as Router } from 'react-router-dom';
class App extends Component {
render() {
return (
<Router>
<Header/>
<Route exact path="/" component={ Home } />
<Route path="/about" component={ About } />
<Route path="/contact" component={ Contact } />
</Router>
);
}
}
export default App;
Now, the result is expected. It is loaded only About component.
Similarly, when you will change the route to /contact
, it will load the content of the Contact component.
Here, as per the every route, component is loaded one by one. Now, we need to set these routes for navigating the components. So, you need to put up these routes for the navigation link respectively.
Create LinkedIn Login in Laravel 8 Using Socialite
Use of Link Component in React JS
For creating any clickable link like anchor tag, you will be having the <Link></Link>
component in React JS. So, in order to navigating component to component, you need to apply it to the Header component inside the Navbar. Let’s do that.
Firstly, switch to the Header.js file and import the Link component.
import { Link } from 'react-router-dom';
After importing the above component, you can use it instead of anchor tag. So, replace all the anchor tag with <Link> from the Header component.
The <Link> component has an attribute named “to” for the redirection. So, let’s checkout the below code.
import React from 'react';
import { Link } from 'react-router-dom';
export default class Header extends React.Component {
render() {
return (
<nav className="navbar navbar-expand-lg navbar-dark bg-dark sticky-top">
<div className="container">
<Link to="/" className="navbar-brand">Programming Fields</Link>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNavAltMarkup">
<ul className="navbar-nav m-auto">
<li className="navbar-item">
<Link to="/" className="nav-link" aria-current="page">Home</Link>
</li>
<li className="navbar-item">
<Link to="/about" className="nav-link">About Us</Link>
</li>
<li className="navbar-item">
<Link to="/contact" className="nav-link">Contact</Link>
</li>
</ul>
</div>
</div>
</nav>
);
}
}
Move back to the browser and check the result. This time, you will be having the redirection through the navigation bar for all components.
But, here something is missed. What if you want to set some style on the active navigation?
We have the another component in React that is <NavLink>
. Let’s see the usage.
Create Socialite Login with Google Account in Laravel 8
Use NavLink Component in React For Active Link
If you are creating a plain link just for anchor then you might use the Link component. But, when you are creating Navigation for the header or something like that then you must use the NavLink component.
import React from 'react';
import { NavLink } from 'react-router-dom';
export default class Header extends React.Component {
render() {
return (
<nav className="navbar navbar-expand-lg navbar-dark bg-dark sticky-top">
<div className="container">
<NavLink to="/" className="navbar-brand">Programming Fields</NavLink>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNavAltMarkup">
<ul className="navbar-nav m-auto">
<li className="navbar-item">
<NavLink to="/" className="nav-link">Home</NavLink>
</li>
<li className="navbar-item">
<NavLink to="/about" className="nav-link">About Us</NavLink>
</li>
<li className="navbar-item">
<NavLink to="/contact" className="nav-link">Contact</NavLink>
</li>
</ul>
</div>
</div>
</nav>
);
}
}
Now, check the result. Here, you can see the About Us link is active and it’s content is loaded. Also, you can check the elements by inspecting it. Here, for the about link there is an active class.
This is only difference of using Link
and NavLink
component in React JS.
Conflict of Having Multiple Same Routes
Sometimes you have multiple routes with the same path but different components. Let me show you an example. Here, I have created one more component named Services.js.
Then imported it inside the App component. Inside the <Router></Router>, we already created some React Routes. Now, add one more route as showing below.
import React, { Component } from 'react';
import Header from './components/Header';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';
import Services from './components/Services';
import { Route, BrowserRouter as Router } from 'react-router-dom';
class App extends Component {
render() {
return (
<Router>
<Header/>
<Route exact path="/" component={ Home } />
<Route path="/about" component={ About } />
<Route path="/about" component={ Services } />
<Route path="/contact" component={ Contact } />
</Router>
);
}
}
export default App;
Here, I have added one more route with the path="/about"
. But, added different component that is Services.
Check the result to get a clear understanding. In the result, you can see both components are rendered because of same path in React Route.
We used the <Router> for wrapping the React Routes. So when you navigate to the route, the React Router DOM searches all the routes from the list one by one. It renders the component on the matching of the path. So, here it founds two routes with the same path. Hence, it rendered both.
In case, if you have these kind of issue then you can fix it by using <Switch> component in Rect JS.
How to Create Facebook Login in Laravel 8 Using Socialite
Use of Switch Component in React JS
The Switch component works really like a switch case in JavaScript or other languages. When you put up the routes inside the <Switch></Switch> component, it will check the request path and render only the first match. Once the match found, it won’t continue the search for the next routes.
In order to use the <Switch> component, you need to import it first.
import React, { Component } from 'react';
import Header from './components/Header';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';
import Services from './components/Services';
import { Route, BrowserRouter as Router, Switch } from 'react-router-dom';
class App extends Component {
render() {
return (
<Router>
<Header/>
<Switch>
<Route exact path="/" component={ Home } />
<Route path="/about" component={ About } />
<Route path="/about" component={ Services } />
<Route path="/contact" component={ Contact } />
</Switch>
</Router>
);
}
}
export default App;
In the result, you will having only the first match of the route path that is About. So, it rendered only About page content.
Conclusion
Finally, we digged deep in React Router DOM for creating and managing React Routes. It is not completed in this one post. I tried to cover the important points but many more are left. We will see in the next post and more in the upcoming posts in the React series. So, I hope you got the concept of using the React Router, BrowserRouter, Link, NavLink, Switch etc. Stay in touch with us for diving more in the React world. Thank you.
Dhrish Shaha says
This is what I was looking for, Thanks a lot for sharing this tutorial.
ABEL says
Thanks for the tutorial. In V6 you have to use element in route.