React Router: React Router is a library for handling navigation in a React application. It enables the navigation of different components in a React application, making it possible to create a Single Page Application (SPA) where the page doesn't reload when navigating between different views.
Exploring Page Navigation with React Router: A Practical Guide
In this blog post, I'll guide you through the process of seamlessly navigating between pages using React Router.
Getting Started: Setting up a React Application with Vite JS
To begin your journey, let's create a new React application using Vite JS. Open your terminal and enter the following command:
npm create vite@latest
You will be prompted to choose a few things, make sure that you choose react and javascript.
The React Router Experience
Once your React application is up and running, we'll dive into the world of React Router. Learn how to efficiently move between pages, enhancing the user experience of your application.
Ready to embark on this journey? Let's get started!
After the project has been created, install the dependencies and open it on the vs code or the code editor of your choice.
cd react-navigation
npm install
code .
When the project is opened on your code editor, install react-router using the following command
npm install react-router-dom
When its completed, navigate to App.jsx
and write the code in this image.
Here we are importing Link
from react-router-dom
. Link
is similar to an a
tag and is used in navigation.
Then open the src
directory and create a folder and name it as pages
.
Inside src/pages
create a file name it About.jsx
and write the code in this image.
Navigate to main.jsx
. This is where we will set up our navigation.
To start, we will have to
- import
About
from./pages/About.jsx
.
import About from "./pages/About.jsx";
- import
createBrowserRouter
andRouterProvider
fromreact-router-dom
.
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import About from "./pages/About.jsx";
- Create our router
const router = createBrowserRouter([
{
path: "/",
element: <App />,
},
{
path: "/about",
element: <About />,
},
]);
We use createBrowserRouter
to create our routes which accepts an array of objects each having a path
and an element
- Replace
<App />
inside the<React.StrictMode></React.StrictMode>
withRouterProvider
and placing therouter
inside it.
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
Top comments (0)