React - utils.ts:781 Uncaught Error: useHref() may be used only in the context of a <Router> component.

문제 상황

  리액트로 페이지 이동을 할 때 보통 Router를 통해서 페이지 네비게이션을 하는데

이때 utils.ts:781 Uncaught Error: useHref() may be used only in the context of a <Router> component.

이라는 오류를 만났다.

 

마침 스택오버플로우에 나와 똑같은 현상을 겪은 사람이 질문을 올려줬고 정확하게 답변해준 사람이 있었다.

https://stackoverflow.com/questions/70220413/error-usehref-may-be-used-only-in-the-context-of-a-router-component-it-wor

 

Error: useHref() may be used only in the context of a <Router> component. It works when I directly put the url as localhost:3000

I have a navbar that is rendered in every route while the route changes on click. ./components/navbar.jsx import React, { Component } from 'react'; import '../App.css'; import { Link } from 'react-...

stackoverflow.com

원인

이유는 간단했다. 

<Link to=> 를 통해서 네비게이팅 하고 있는 컴포넌트가 Router안에 포함되지 않았기 때문에  

Router 링크가 관리하고 있는 링크들을 인식하지 못했던 것이었다.

 

위 내용에서 해결방법을 발췌하면 아래와 같다.

 

Issue

You are rendering the navbar outside the routing context. The Router isn't aware of what routes the links are attempting to link to that it is managing. The reason routing works when directly navigating to "/experiences" is because the Router is aware of the URL when the app mounts.

<Navbar /> // <-- outside router!!

<Router>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/experiences" element={<Experiences />} />
  </Routes>
</Router>

Solution

Move it inside the routing context so the Router is aware and can manage routing correctly.

<Router>
  <Navbar />
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/experiences" element={<Experiences />} />
  </Routes>
</Router>

 

'React' 카테고리의 다른 글

React - useEffect()  (2) 2023.10.29
React - State 개념과 useState Hook  (0) 2022.09.03
React - component 합성과 추출  (0) 2022.09.03
React - Component 개념 정리  (0) 2022.09.02
React - props  (0) 2022.08.29