In this tutorial, we'll talk about What’s New in React Router v6. React Router is a package for client and server-side routing library in Reactjs. React Router runs anywhere from one page to another on the web page.There are many libraries like react router, BrowserRouter, Routes, Route, useParams, Outlet, Link, useNavigate, useRouteMatch... etc.Scroll down to the page so you can see the full source code available for this.

In v6 big change the powerful new element and reduced smaller bundle size means your react app loads faster in slow(or)poor network connections.

How to Install React Router

Create your react project. In your terminal/command line enter:

npx create-react-app react-router-v6
cd react-router-v6
npm install react-router-dom@6
npm start 

Next, Project structure your folder as follows.

src
├── components
|   ├── Nav.css
|   ├── Nav.js
├── page
|   ├── About.js
|   ├── AdminDashboard.js
|   ├── Home.js
|   ├── OrderDetails.js
|   ├── Orders.js
|   ├── RouteAsObj.js
|   ├── Search.js
|   ├── Style.css
|   ├── UserDashboard.js
|   ├── UserEditProfile.js
|   └── UserProfile.js
├── App.css
├── App.js
├── index.css
└── index.js 

Now, open the index.js file in the src folder the App component with import the BrowserRouter component from react-router-dom.

Index.js
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter } from "react-router-dom"; import './index.css'; import App from './App'; ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter>, document.getElementById("root") );
App.js
import { Route, Routes } from "react-router-dom"; import "./App.css"; import Nav from "./components/Nav"; import Home from "./page/Home"; import About from "./page/About"; import UserDashboard from "./page/UserDashboard"; import UserProfile from "./page/UserProfile"; import UserEditProfile from "./page/UserEditProfile"; import AdminDashboard from "./page/AdminDashboard"; import RouteAsObj from "./page/RouteAsObj"; import Search from "./page/Search"; function App() { return ( <div className='app'> <Nav /> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> {/* Approach #1 */} <Route path="/user"> <Route index element={<UserDashboard />} /> <Route path="profile" element={<UserProfile />} /> <Route path=":editId" element={<UserEditProfile />} /> </Route> {/* Approach #2 */} <Route path="admin/*" element={<AdminDashboard />} /> <Route path="object_route/*" element={<RouteAsObj />} /> <Route path="search" element={<Search />} /> <Route path="*" element={<NotFound />} /> </Routes> </div> ); } export const NotFound = () => { return <div><h1> This is a 404 page </h1> </div> } export default App;
Nav.js
import { NavLink, Outlet } from "react-router-dom"; import "./Nav.css"; const Nav = () => { return ( <div className='nav'> <div className='nav__container'> {/* Approach #1 --- Active */} <NavLink className={({ isActive }) => isActive ? "active" : ""} to="/">Home</NavLink> {/* Approach #2 --- Active */} <NavLink style={({ isActive }) => { return { color: isActive ? "#ffe500" : "" }; }} to="/about">About</NavLink> <NavLink className={({ isActive }) => isActive ? "active" : ""} to="/user">User Dashboard</NavLink> <NavLink className={({ isActive }) => isActive ? "active" : ""} to="/admin">Admin Dashboard</NavLink> <NavLink className={({ isActive }) => isActive ? "active" : ""} to="/object_route"> Route as Object </NavLink> <NavLink className={({ isActive }) => isActive ? "active" : ""} to="/search"> Search </NavLink> <Outlet /> </div> </div> ); }; export default Nav;
UserDashboard.js
import React from 'react' import { Link } from "react-router-dom"; import "./Style.css"; const UserDashboard = () => { let ids=1007; return ( <div className='user__dashboard'> <h1> User Dashboard </h1> <Link to="profile" className='btn'> User Profile </Link> <Link to={`/user/${ids}`} className='btn'> Edit Profile</Link> </div> ) } export default UserDashboard
UserProfile.js
import React from 'react' import { useNavigate } from "react-router-dom"; const UserProfile = () => { const navigate = useNavigate(); return ( <div> <h1> User Profile</h1> <button onClick={() => navigate(-1)}>Go back</button> </div> ) } export default UserProfile
UserEditProfile.js
import React from 'react' import { useNavigate, useParams } from "react-router-dom"; import "./Style.css"; const UserEditProfile = () => { let params = useParams(); let navigate = useNavigate(); const handleClick =()=> { navigate('/user/profile'); }; return ( <div> <h1> Edit Profile </h1> <p> <b> Profile Id </b> : {params.editId} </p> <button onClick={handleClick} className='btn__button'> useNavigate Instead of useHistory </button> </div> ) } export default UserEditProfile
AdminDashboard.js
import React from "react" import {NavLink, Routes, Route, Outlet } from "react-router-dom" import Orders from "./Orders"; import OrderDetails from "./OrderDetails"; import "./Style.css"; const AdminDashboard = () => { return ( <div className='admin__dashboard'> <h1> Admin Dashboard</h1> <ul> <li> <NavLink className={({ isActive }) => isActive ? "active" : ""} to="profile">Profile</NavLink> </li> <li> <NavLink className={({ isActive }) => isActive ? "active" : ""} to="orders">Orders</NavLink> </li> <li> <NavLink className={({ isActive }) => isActive ? "active" : ""} to="review">Review</NavLink> </li> </ul> <div className="dashboard"> <Routes> <Route path="profile" element={<Profile />}></Route> <Route path="orders" element={<Orders />}></Route> <Route path="review" element={<Review />}></Route> <Route path="order_details/:orderId" element={<OrderDetails />} /> </Routes> </div> <Outlet /> </div> ) } export const Profile = () => { return <h2>Profile</h2> } export const Review = () => { return <h2>Review</h2> } export default AdminDashboard
Orders.js
import React from 'react' import { Link } from "react-router-dom" const Orders = () => { const orderIds = ["10001", "10002", "10003"] return (<> <h2>Orders</h2> <ul className="orders"> {/* Loop through the orders array and display link to order details */} {orderIds.map(orderId => { return ( <li key={orderId}> <Link to={`/admin/order_details/${orderId}`}> View Order {orderId} </Link> </li> ) })} </ul> </> ) } export default Orders
OrderDetails.js
import React from 'react' import { useParams,useNavigate } from "react-router-dom" const OrderDetails = () => { const params = useParams() const navigate = useNavigate() const onBackClick = e => { e.preventDefault() navigate("/admin/orders") } return ( <div> <h2>Details of order {params.orderId}</h2> <a href="#" onClick={onBackClick}> Back to Orders</a> </div> ) } export default OrderDetails
RouteAsObj.js
import React from "react" import { useRoutes, Outlet } from "react-router" import { Link } from "react-router-dom" const RouteAsObj = () => { let element = useRoutes([ { path: "/", element: <Route1 /> }, { path: "route2", element: <Route2 /> }, { path: "route3",element: <Route3 />, // children can be used to configure nested routes children: [ { path: "child1", element: <Child1 /> }, { path: "child2", element: <Child2 /> }, ], }, { path: "*", element: <NotFound /> }, ]) return ( <div className='admin__dashboard'> <ul> <li> <Link to="">Route1</Link> </li> <li> <Link to="route2">Route2</Link> </li> <li> <Link to="route3">Route3</Link></li> </ul> {element} </div> ) } const Route1 = () => <h1>Route1</h1> const Route2 = () => <h1>Route2</h1> const Route3 = () => { return ( <div> <h1>Route3</h1> <ul> <li> <Link to="child1">Child1</Link> </li> <li> <Link to="child2">Child2</Link> </li> </ul> <Outlet /> </div> ) } const Child1 = () => <h2>Child1</h2> const Child2 = () => <h2>Child2</h2> const NotFound = () => <h1>NotFound</h1> export default RouteAsObj
Search.js
import React, { useRef } from "react" import { useLocation, useNavigate } from "react-router-dom" function useQuery() { // Use the URLSearchParams API to extract the query parameters // useLocation().search will have the query parameters eg: ?term=bar&a=b return new URLSearchParams(useLocation().search) } const Search = () => { const query = useQuery() const term = query.get("term") const inputRef = useRef(null) const navigate = useNavigate() const formSubmitHandler = e => { //prevent the default form submission e.preventDefault() //extract search term using refs. const searchValue = inputRef.current.value navigate(`?term=${searchValue}`) } return ( <div> <h1> Search </h1> <form action="" onSubmit={formSubmitHandler}> <input type="text" name="term" ref={inputRef} /> <input type="submit" value="Search" /> {/* Display the search term if it is present */} {term && <h2>Results for '{term}'</h2>} </form> </div> ) } export default Search

– The component will renders the matching child route’s path.

useNavigate Instead of useHistory

– react router library in v5

– lreact router ibrary in v6

Now react router v5 history.push() will be replaced with v6 navigate():

Download

Related keywords

  • React - Introduction to router v6
  • Introduction to react router v6
  • New in React Router v6?
  • React navbar
  • Responsive navbar
  • React-router v6 Outlet
  • useNavigate react-router v6
  • Redirect in react-router v6
  • React router v6 npm
  • React-router v6 authentication
  • Protected route react-router-dom v6
  • React router v6 default Route
  • React-router private route
  • React-router v6 redirect
  • React-router authenticated routes
  • This website show country are united states, France, Canada, japan, New york, london, Los Angeles, Russia, Italy, Spain, Austria, Serbia, Moldova, Bosnia and Herzegovina, Albania, Lithuania, North Macedonia, Switzerland, Bulgaria, Denmark,Germany, United Kingdom.