[React-Router v6] useMatch

이춘구·2022년 2월 2일
2

React-Router v5의 useRouterMatch가 v6로 넘어오면서 useMatch로 변경되었다.
useMatch()의 인자로 url을 넘기면 해당 url과 일치할 경우 url의 정보를 반환하고, 일치하지 않을 경우 null을 반환한다.

  • 일치할 경우

  • 일치하지 않을 경우

이를 이용해서 여러 개의 탭 중 현재 보여지고 있는 탭에만 accent color를 줄 수 있다.

import { useMatch } from "react-router-dom";
import styled from "styled-components";

const Tab = styled.span<{ isActive: boolean }>`
	color: ${(props) =>
    	props.isActive ? props.theme.accentColor : props.theme.textColor};
`;

const Coin = () => {
  const matchPriceTab = useMatch("/:coinId/price");
  const matchChartTab = useMatch("/:coinId/chart");
  
  return (
  	<Tab isActive={matchPriceTab !== null}>
    	<Link to={`/${coinId}/price`}>Price</Link>
	</Tab>
  	<Tab isActive={matchChartTab !== null}>
    	<Link to={`/${coinId}/chart`}>Chart</Link>
	</Tab>
  )
}
profile
프런트엔드 개발자

0개의 댓글

관련 채용 정보