React-Router-Dom v6 Setup

·

2 min read

This article is a walkthrough on how to setup react-router-dom-v6

To install react-router-dom v6 in the terminal run:

npm install react-router-dom@6

Assuming you already created a react application. In the index.js file, import createBrowserRouter and RouterProvider from react-router-dom. The createBrowserRouter function will create the routes and RouterProvider will communicate the routes to your application when you use the NavLink components(from react-router-dom) in the NavBar component.

//index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import {createBrowserRouter, RouterProvider} from 'react-router-dom'
import routes from './routes'

const router = createBrowserRouter(routes)
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <RouterProvider router={router}/>
  </React.StrictMode>
);

Next, create a routes.js file in the src folder. When you import routes in the index.js file make sure you point to the path you placed the routes.js file in. If you want to have nested routes. I wrote this article to help you setup react-router-dom-v6 with nested routes. To setup without nested navigation, in routes.js, set your routes as follows:

//routes.js
import Home from './pages/Home'
import About from './pages/About'
import Login from './pages/Login'

const routes =[
      {
        path: "/",
        element: <Home />
      }, 
      {
        path: "/about",
        element: <About />
      },
      {
        path: "/login",
        element: <Login />
      }
]

export default routes

Now, we have to create the links. We can use Link or NavLink from react-router-dom. Create a Navbar.js component and add the links.

//In NavBar.js
import { NavLink } from "react-router-dom";
function NavBar() {
    return (
        <nav>
            <NavLink
                to="/"
            >
                Home
            </NavLink>
            <NavLink
                to="/about"
            >
                About
            </NavLink>
            <NavLink
                to="/login"
            >
                Login
            </NavLink>
        </nav>
    )
}
export default NavBar

You're all set! Now just create the home, about, and login components and format them however you want.