Javascript/React

[React] 🧭 Router useMatch 사용법 - component에서 router path형식 비교하기

react-router-dom 버전 6에서는 matchPath 함수가 제거되었다. 대신, 매치 정보를 얻기 위해 useMatch 훅을 사용할 수 있다.

useMatch 훅은 현재 경로와 지정된 경로 패턴을 비교하여 매치 여부를 확인하고, 매치된 정보를 반환한다.

 

사용법

import { useLocation, useMatch } from 'react-router-dom';

function MyComponent() {
  const location = useLocation();
  const match = useMatch('/myroute');

  useEffect(() => {
    const routePath = match ? match.path : '';

    console.log(routePath); // path props 값 출력
  }, [match]);

  // ...

}

 

예시 example

//비교하고자 하는 router path : '/share/:id'

// ✅ true
// page path : '/share/170'
 const isMatchPath = useMatch('/share/:id'); 
   useEffect(() => {
   console.log(isMatchPath); //{pathname: '/share/170', search: '', hash: '', state: null, key: 'default'}
  }, []);
  
  
// ✅ true
// page path : '/share/170?limit=10&page=15'
const isMatchPath = useMatch('/share/:id'); 
   useEffect(() => {
   console.log(isMatchPath); //{pathname: '/share/170', search: '?limit=10&page=15', hash: '', state: null, key: 'default'}
  }, []);

  
// ❌ false
// page path : '/report/:id'
 const isMatchPath = useMatch('/share/:id'); 
   useEffect(() => {
   console.log(isMatchPath); //null
  }, []);
  
  
  // ❌ false
  // page path : '/signin'
 const isMatchPath = useMatch('/share/:id'); 
   useEffect(() => {
   console.log(isMatchPath); //null
  }, []);

 

공식 문서

728x90
반응형