DEV Community

Frédéric Speter
Frédéric Speter

Posted on

Lost location.pathname

Hello,

I'm a beginner in ReactJS.
I make a component for my menu like this :

import React from 'react'
import {NavLink,useLocation} from 'react-router-dom'


export default function Navigation() {
        //For active link
        const location = useLocation()
        const getNavLinkClass = (path) => {
          return location.pathname === path ? 'active' : '';
        }

return (
...<li className={getNavLinkClass("/page")}> <NavLink  to={page.slug}>{page.title}</NavLink></li>...

Enter fullscreen mode Exit fullscreen mode

It's work fine, but i need to call Api to get Pages, i do that :

import React,{useState,useEffect} from 'react'
import {NavLink,useLocation} from 'react-router-dom'
import axios from 'axios'

export default function Navigation() {

        const [data,setData] = useState([])

        //For Active
        const location = useLocation()
        const getNavLinkClass = (path) => {
                    return loc.pathname === path ? 'active' : '';
        }


        useEffect(() => {

            const fetchData = async () => {
                const result = await axios.get('http://localhost:5000/menu')

                setData(result.data)
            }
            fetchData()
        },[])


        return (
...<li className={getNavLinkClass("/page")}> <NavLink  to={page.slug}>{page.title}</NavLink></li>...

Enter fullscreen mode Exit fullscreen mode

I have this error :
TypeError: Cannot read properties of undefined (reading 'pathname')

I don't understand.

Thaks for help

Discussion (1)

Collapse
fspeter profile image
Frédéric Speter Author

ok,
the problem is from à NavLink without "TO" property ...