2

I am building a react page so I divided the page section into components. but my navbar is not redirecting to the component section.i am using react-router@6 Can anybody suggest how I can get the navbar to consistently detect when the route changes? Thank you!

App.js

import React from "react";
import Navbar from "./Component/Navbar";
import Gallary from "./Component/Gallary";
import { BrowserRouter, Routes, Route } from "react-router-dom";
export const App = () => {
  return (
    <div>
      <Navbar />
      <BrowserRouter>
        <div>
          <Routes>
            <Route path="gallary" element={<Gallary />}></Route>
          </Routes>
        </div>
      </BrowserRouter>
      <Gallary />
    </div>
  );
};

export default App;

Navbar.jsx

import { Link } from "react-router-dom";
export const Navbar = () => {
  return (
    <div className="px-4 py-5 mx-auto sm:max-w-xl md:max-w-full lg:max-w-screen-xl md:px-24 lg:px-8">
      <div className="relative flex grid items-center grid-cols-2 lg:grid-cols-3">
        <ul className="flex items-center hidden space-x-8 lg:flex">
          <li>
            <Link
              to="/Gallary"
              aria-label="About"
              title="About"
              classNameName="font-medium tracking-wide text-white-700 transition-colors duration-200 hover:text-deep-purple-accent-400"
            >
              Photo Gallary
            </Link>
          </li>
        </ul>
      </div>
    </div>
  );
};
export default Navbar;

  • const navigate = useNavigate(); .pass a prop to link onClick = {()=>navigate('/requied location')} – Shah Vipul Aug 21 '22 at 11:00
  • I guess it's giving you `useHref() may be used only in the context of a component.` error . maybe you should update your question and add this error to make it clear for other people facing the same error – monim Aug 21 '22 at 11:34

1 Answers1

1

Make sure that all components in which you use links are nested inside of a BrowserRouter otherwise the context that links rely on is not available. In your case Navbar component is using a link :

<Link
              to="/Gallary"
              aria-label="About"
              title="About"
              classNameName="font-medium tracking-wide text-white-700 transition-colors duration-200 hover:text-deep-purple-accent-400"
            >
              Photo Gallary
            </Link>

so you should wrap your Navbar inside BrowserRouter

just change your App.js like this :

import React from "react";
import Navbar from "./Component/Navbar";
import Gallary from "./Component/Gallary";
import { BrowserRouter, Routes, Route } from "react-router-dom";
export const App = () => {
  return (
<BrowserRouter>
    <div>
      <Navbar />
      
        <div>
          <Routes>
            <Route path="gallary" element={<Gallary />}></Route>
          </Routes>
        </div>
     
      <Gallary />
    </div>
 </BrowserRouter>
  );
};

export default App;
monim
  • 3,641
  • 2
  • 10
  • 25