Skip to content
Advertisement

props.location is undefined with route component

i’m trying to run snippet code as below:

JavaScript

i want to get the path at Challenges route component but it throw an error: Cannot read properties of undefined (reading ‘pathname’) i try to log variable “a” and “window.location” to test and it log two times like this:

JavaScript

My question is why i can’t take value of props.location.pathname and why its run two times and the second time it throw an error why not at fisrt time. Thank for helping me! Hope you have a good day.

Advertisement

Answer

Issue(s)

  1. react-router-dom v6 Route components rendered via the element prop don’t receive route props.
  2. Route children components must use react hooks to access the route context, i.e. useParams, useLocation, useNavigate, etc… and therefore must be function components.
  3. The console.log calls are in the function body so these are unintentional side-effects. This is likely why they are called twice, assuming the app is being rendered into a React.StrictMode component.

Solution

Challenges should use the uselocation hook to access the pathname. Move the console logs into an useEffect hook so they are called once per render to the DOM.

JavaScript

v6 api-reference

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