Search code examples
reactjsreact-router-dom

React router 6, useNavigate how to get pathname


I am trying to understand how to use react router 6 and useNavigate but can't figure out how to get the current pathname.

Using useHistory I could use history.location.pathname to get the current url. But how do I do the same using useNavigate?

import React, {useState} from 'react'
import styed from 'styled-components'
import { useNavigate } from 'react-router-dom'
import { MovieState } from '../movieState'

export const MovieDetail = () => {
    let navigate = useNavigate();
    const [movies, setMovies] = useState(MovieState)
    const [movie, setMovie] = useState(null)
    //const url = navigate.location.pathname;
    return (
        <div>
            <h1>MovieDetail</h1>
        </div>
    )
}


Solution

  • If you need access to location.pathname, use useLocation hook:

    import {  useLocation } from 'react-router-dom';
    
     const App = () => {
      const location = useLocation();
      console.log(location.pathname)  
      //...
    };