skip to Main Content

How to handle this error in react js

Error: useNavigate() may be used only in the context of a <Router> component.
▶ 3 stack frames were collapsed.
Navbar
C:/Users/dell/OneDrive/Desktop/ReactJs/react-learning/src/components/Navbar.js:9
   6 | import { Routes , Route , useNavigate} from "react-router-dom";
   7 | 
   8 | export default function Navbar() {
>  9 |   const navigate = useNavigate();
  10 | 
  11 |   const navigateToExperience =() =>{
  12 |     navigate('/experience');

I try to redirect the multiple page in navbar.

Code:

Navbar.js

import React from "react";
import { Routes , Route , useNavigate} from "react-router-dom";

export default function Navbar() {
  const navigate = useNavigate();

  const navigateToExperience =() =>{
    navigate('/experience');
  };
  const navigateToProjects =() =>{
    navigate('/projects');
  };
  const navigateToEducation =() =>{
    navigate('/education');
  };
  const navigateToSkills =() =>{
    navigate('/skills');
  };
  const navigateToContact =() =>{
    navigate('/contact');
  };
  const navigateToAbout =() =>{
    navigate('/about');
  };
  return (
   
    <div>
      <nav
        className="navbar navbar-expand-lg navbar-light bg-light"
        id="fitnav"
      >
        <div className="container-fluid">
          <a className="navbar-brand" href="/">
            Shivam Curriculum vitae
          </a>
          <button
            className="navbar-toggler"
            type="button"
            data-bs-toggle="collapse"
            data-bs-target="/navbarText"
            aria-controls="navbarText"
            aria-expanded="false"
            aria-label="Toggle navigation"
          >
            <span className="navbar-toggler-icon"></span>
          </button>
          <div className="collapse navbar-collapse" id="navbarText">
            <ul className="navbar-nav me-auto mb-2 mb-lg-0" id="navbarCenter">
              <li className="nav-item">
                <a className="nav-link active" aria-current="page" href="/">
                  Home
                </a>
              </li>
              <li className="nav-item">
                <a className="nav-link" href={navigateToExperience}>
                  Experience
                </a>
                <Routes>
                  <Route path="/experience" element={<experience/>} />
                </Routes>
              </li>
              <li className="nav-item">
                <a className="nav-link" href={navigateToProjects}>
                  Projects
                </a>
                <Routes>
                  <Route path="/" element={<projects/>}/>
                </Routes>
              </li>
              <li className="nav-item">
                <a className="nav-link" href={navigateToEducation}>
                  Education
                </a>
                <Routes>
                  <Route path="/" element={<education/>}/>
                </Routes>
              </li>
              <li className="nav-item">
                <a className="nav-link" href={navigateToSkills}>
                  Skills
                </a>
                <Routes>
                  <Route path="/" element={<skills/>}/>
                </Routes>
              </li>
              <li className="nav-item">
                <a className="nav-link" href={navigateToAbout}>
                  About Us
                </a>
                <Routes>
                  <Route path="/" element={<about/>}/>
                </Routes>
              </li>
              <li className="nav-item">
                <a className="nav-link" href={navigateToContact}>
                  Contact Us
                </a>
                <Routes>
                  <Route path="/" element={<contact/>}/>
                </Routes>
              </li>
            </ul>
            <span className="navbar-text">
              My All Skills and Projects are show here!!
            </span>
          </div>
        </div>
      </nav>
    </div>

  );
}

App.js

import "./App.css";
import React from "react";
import Navbar from "./components/Navbar";
import Intro from "./components/Intro";
import Education from "./components/Education";
import Project from "./components/Project";
import Contactform from "./components/Contactform";
import Footer from "./components/Footer";
import img1 from "./images/profilepic.jpg";
function App() {
  return (
    <>
      <body>
        <div className="navcolor">
        <Navbar />
        </div>
        <div className="mainpostion">
          <div className="postion">
            <img src={img1} alt="" />
          </div>
          <div className="postion2">
            <Intro />
          </div>
        </div>
        <div className="container">
          <Education />
        </div>
        <div className="container-mb-3">
          <div className="projecthead">
            <h1>Our Projects And Discription ... </h1>
          </div>
          <Project />
        </div>

        <div className="container" id="adjust">
          <h1>Contact us for Hireing me ..</h1>
          <Contactform />
        </div>
        <div>
          <Footer />
        </div>
      </body>
    </>
  );
}

export default App;

2

Answers


  1. The useNavigate hook can only be used within the routing context provided by a router, e.g. BrowserRouter, etc. Move Navbar such that it is rendered under a router component. In this case the App component imports a router and renders its content into it.

    Example App.js:

    import "./App.css";
    import React from "react";
    import { BrowserRouter } from 'react-router-dom';
    import Navbar from "./components/Navbar";
    ...
    
    function App() {
      return (
        <BrowserRouter>   // <-- provides routing context
          <body>
            <div className="navcolor">
              <Navbar />  // <-- uses `useNavigate` hook which consumes routing context
            </div>
            ...
          </body>
        </BrowserRouter>
      );
    }
    

    Since you need only one router (and routing context) per React app, it’s common to render the router at the root, wrapping the App component.

    Example index.js:

    import { StrictMode } from "react";
    import { createRoot } from "react-dom/client";
    import { BrowserRouter as Router } from "react-router-dom";
    import App from "./App";
    
    const rootElement = document.getElementById("root");
    const root = createRoot(rootElement);
    
    root.render(
      <StrictMode>
        <Router>
          <App />
        </Router>
      </StrictMode>
    );
    

    Additionally, the Navbar component should be rendering the Link component instead of raw anchor tags (<a>). In doing so there’s no need to use the useNavigate hook and navigate functions and callbacks. The routes should probably not be rendered in the navbar, but out in the content area in App.

    Navbar

    import React from "react";
    import { Routes, Route, Link } from "react-router-dom";
    
    export default function Navbar() {
      return (
        <div>
          <nav
            className="navbar navbar-expand-lg navbar-light bg-light"
            id="fitnav"
          >
            <div className="container-fluid">
              <Link className="navbar-brand" to="/">
                Shivam Curriculum vitae
              </Link>
              <button
                className="navbar-toggler"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="/navbarText"
                aria-controls="navbarText"
                aria-expanded="false"
                aria-label="Toggle navigation"
              >
                <span className="navbar-toggler-icon"></span>
              </button>
              <div className="collapse navbar-collapse" id="navbarText">
                <ul className="navbar-nav me-auto mb-2 mb-lg-0" id="navbarCenter">
                  <li className="nav-item">
                    <Link className="nav-link active" aria-current="page" to="/">
                      Home
                    </Link>
                  </li>
                  <li className="nav-item">
                    <Link className="nav-link" to="/experience">
                      Experience
                    </Link>
                  </li>
                  <li className="nav-item">
                    <Link className="nav-link" to="/projects">
                      Projects
                    </Link>
                  </li>
                  <li className="nav-item">
                    <Link className="nav-link" to="/education">
                      Education
                    </Link>
                  </li>
                  <li className="nav-item">
                    <Link className="nav-link" to="/skills">
                      Skills
                    </Link>
                  </li>
                  <li className="nav-item">
                    <Link className="nav-link" to="/about">
                      About Us
                    </Link>
                  </li>
                  <li className="nav-item">
                    <Link className="nav-link" to="/contact">
                      Contact Us
                    </Link>
                  </li>
                </ul>
                <span className="navbar-text">
                  My All Skills and Projects are show here!!
                </span>
              </div>
            </div>
          </nav>
        </div>
      );
    }
    
    function App() {
      return (
        <BrowserRouter>
          <body>
            <div className="navcolor">
              <Navbar />
            </div>
            
            <Routes>
              <Route path="/" element={/* Home page content */} />
              <Route path="/experience" element={<Experience />} />
              <Route path="/projects" element={<Projects />} />
              <Route path="/education" element={<Education />} />
              <Route path="/skills" element={<Skills />} />
              <Route path="/about" element={<About />} />
              <Route path="/contact" element={<Contact />} />
            </Routes>
    
            <div>
              <Footer />
            </div>
          </body>
        </BrowserRouter>
      );
    }
    
    Login or Signup to reply.
  2. Your error "useNavigate() may be used only in the context of a component" arises because the useNavigate hook can only be used within components that are descendants of a BrowserRouter or Router component. The Router component is what provides the context that useNavigate needs to function.

    Additionally, in your current code you’re trying to pass a function to href which is incorrect. The href attribute expects a string value. Instead of this, you should make use of onClick event to handle the navigation upon clicking.

    Here’s how you could modify your Navbar component:

    import React from "react";
    import { Routes, Route, useNavigate } from "react-router-dom";
    
    export default function Navbar() {
      const navigate = useNavigate();
    
      return (
        <div>
          <nav className="navbar navbar-expand-lg navbar-light bg-light" id="fitnav">
            <div className="container-fluid">
              <a className="navbar-brand" onClick={() => navigate("/")}>
                Shivam Curriculum vitae
              </a>
              <ul className="navbar-nav me-auto mb-2 mb-lg-0" id="navbarCenter">
                <li className="nav-item">
                  <a className="nav-link active" aria-current="page" onClick={() => navigate("/")}>
                    Home
                  </a>
                </li>
                <li className="nav-item">
                  <a className="nav-link" onClick={() => navigate("/experience")}>
                    Experience
                  </a>
                </li>
                <li className="nav-item">
                  <a className="nav-link" onClick={() => navigate("/projects")}>
                    Projects
                  </a>
                </li>
                <li className="nav-item">
                  <a className="nav-link" onClick={() => navigate("/education")}>
                    Education
                  </a>
                </li>
                <li className="nav-item">
                  <a className="nav-link" onClick={() => navigate("/skills")}>
                    Skills
                  </a>
                </li>
                <li className="nav-item">
                  <a className="nav-link" onClick={() => navigate("/about")}>
                    About Us
                  </a>
                </li>
                <li className="nav-item">
                  <a className="nav-link" onClick={() => navigate("/contact")}>
                    Contact Us
                  </a>
                </li>
              </ul>
              <span className="navbar-text">
                My All Skills and Projects are show here!!
              </span>
            </div>
          </nav>
        </div>
      );
    }
    

    Remember, for this to work properly, your Navbar component should be rendered as a child of a BrowserRouter or Router component. Typically, this is done in your top-level App component:

    import React from 'react';
    import { BrowserRouter as Router } from 'react-router-dom';
    import Navbar from './Navbar';
    
    function App() {
      return (
        <Router>
          <Navbar />
          {/* Your routes here */}
        </Router>
      );
    }
    
    export default App;
    

    The Routes and Route components should be also wrapped within a BrowserRouter or Router component. This is typically done in your main App component where you define the main routes of your application.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search