Skip to content
Advertisement

(react router v6) “Error: useNavigate() may be used only in the context of a component” error in hoc component

In the Router section, I try to check whether the user has access to the component using the higher order component (hoc).

Therefore, check whether the user is logged in at the hoc. At this time, an attempt to access each page may be prevented or forced to move to another page according to the response value.

In order to move to another page, we need to use the “navigate” method in the hoc component.

However, when using the navigate method, the phrase "Error: use Navigate() may be used only in the context of a <Router> component" appears.

Since hoc is used in the router, I’m going to use Navigate. I think I can do it.

Can you tell me what the problem is? What am I missing here? It’s my first time trying the backend, so please understand.

src/App.js

JavaScript

src/hoc/auth.js (Auth)

JavaScript

index.js

JavaScript

Advertisement

Answer

Update your HOC as

Note: Calling a component as Function rather than JSX Element may lead to unexpected bugs and also creates issues with the usage of Hooks.

Check out this link for more understanding about Calling as Component vs Calling As Function: https://dev.to/igor_bykov/react-calling-functional-components-as-functions-1d3l

(Goto heading What is a Component at all? )

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement