Steps to Create Implement useRoutes Hook
Step 1: Create a React application using the following command:
npx create-react-app useroutes
Step 2: After creating your project folder(i.e. gfg), move to it by using the following command:
cd useroutes
Step 3: Install React Router library
npm install react-router-dom
Folder Structure:
Dependencies: The updated dependencies in package.json file will look like.
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Example: This below example demonstrate the use of useRoutes hook.
Javascript
//src/App.js import "./App.css" ; import { BrowserRouter } from "react-router-dom" ; import Router from './router' export default function App() { return ( <BrowserRouter> <div className= "App" > <h1 style={{ color: "green" }}> w3wiki | useRoutes Example</h1> <Router /> </div> </BrowserRouter> ); } |
Javascript
//src/Navigation.js import { Link, Outlet } from "react-router-dom" ; export default function Navigation() { return ( <> <nav> <ul> <li> <Link to= "/" >Home</Link> </li> <li> <Link to= "about" >About</Link> </li> <li> <Link to= "course" >Course</Link> </li> </ul> </nav> <Outlet /> </> ); } |
Javascript
//src/router.js import { useRoutes } from "react-router-dom" ; import Navigation from "./Navigation" ; const Home = () => <h1>Home Page</h1> const About = () => <h1>About Page</h1> const Course = () => <h1>Course Page</h1> export default function Router() { let element = useRoutes([ { element: <Navigation />, children: [ { path: "/" , element: <Home /> }, { path: "about" , element: <About /> } ] }, { element: <Navigation />, children: [ { path: "course" , element: <Course /> } ] }, { path: '*' , element: <div>404 Not Found</div> }, ]); return element; } |
To run the application use the following command:
npm run start
Output: Now go to http://localhost:3000 in your browser:
useRoutes Hook in React Router
React Router is a library that is used for handling navigation and routing in React applications. It provides a way to navigate between different components or pages while maintaining a single-page application (SPA) structure. One of the key features is the useRoutes hook. It allows you to define routes in a declarative manner. In this article, we will learn about useRoutes hook with its syntax and example.