• Feed
  • Explore
  • Ranking
/
/
    ⚛️ React

    react-router에서 useMatch로 현재 route path 확인하기

    Reactreact-router
    m
    morethanmin
    2024.07.09
    ·
    1 min read

    until-802

    react-router v6 이후부터는 useRouterMatch 가 사라지고 useMatch로 대체되었습니다.

    사용법은 이전과 동일하지만, 공식문서에 example이 아직 없는 것 같아 짧게 정리해 봅니다.

    사용법

    예시는 until 에서 사용되는 route를 기준으로 작성했습니다.

    일치하는 path가 있는 경우에는 path 객체를 return하고, 일치하지 않는 경우에는 null을 return합니다.

    // current path : '/@morethanmin'
     const match = useMatch('/:username'); 
       useEffect(() => {
       console.log(match); //{pathname: '/@morethanmin', search: '', hash: '', state: null, key: 'default'}
      }, []);
      
      
    // current path : '/@morethanmin?tab=overview'
    const match = useMatch('/share/:id'); 
       useEffect(() => {
       console.log(match); //{pathname: '/@morethanmin', search: '?tab=overview', hash: '', state: null, key: 'default'}
      }, []);
    
      
    // current path : '/explore'
     const match = useMatch('/share/:id'); 
       useEffect(() => {
       console.log(match); //null
      }, []);






    - 컬렉션 아티클