Routing in SPA using React Router

Routing in SPA using React Router

Before we start with React Router, there is a question that needs to be answered - What is SPA?

Single Page Application

SPA is that kind of application where the user clicks some links and the data of the page gets updated but the page doesn't reload. Only the content of the page gets updated and the user stays on the same page for the whole application.

React Router

React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.

Here, we'll be using React Router v6.

Let's do it

  • Step - 1

Create your app and install the react-router in your project.

npx create-react-app my-app

npm i react-router-dom@next history
  • Step - 2

Import BrowserRouter from react-router-dom inside index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter as Router } from "react-router-dom";

ReactDOM.render(
  <React.StrictMode>
    <Router>
      <App />
    </Router>
  </React.StrictMode>,
  document.getElementById('root')
);
  • Step - 3

Import Routes, Route from react-router-dom inside App.js to set the components to be displayed on the specific route.

Here, path will be added to the URL, and the element is the component that will be displayed on that URL.

import './App.css';
import { Route, Routes } from "react-router-dom";
import { Nav } from "./Components";
import { Home, Profile, About } from "./Pages";

function App() {
  return (
    <div className="App">
      <Nav />
      <Routes>
        <Route path='/' element={<Home />} />
        <Route path='/profile' element={<Profile />} />
        <Route path='/about' element={<About />} />
      </Routes>
    </div>
  );
}

export default App;
  • Step - 3

Import NavLink from react-router-dom inside NavBar to navigate the user to a specific path.

import { NavLink } from "react-router-dom";
import './nav.css';

function Nav() {
  return (
    <nav>
      <ul className="header">
        <li><NavLink to="/">Home</NavLink></li>
        <li><NavLink to="/profile">Profile</NavLink></li>
        <li><NavLink to="/about">About</NavLink></li>
      </ul>
    </nav>
  );
}
export default Nav;

And we've completed the routing for our React App.

Conclusion

I hope this will help you to set up the routing in your app. Later, I'll write another blog on the more concepts of react-router like useNavigate, useParams, and useLocation.

Do share your feedback in the comments and help me to improve.

ThankYou for reading :)