-
[React] NavLink웹 프로그래밍 2025. 1. 1. 18:49
Link
- 라우터 내에서 직접적으로 페이지 이동을 하고자 할 때 사용되는 컴포넌트
- html의 <a> 태그와 비슷한 역할을 한다
import React from 'react'; import {Link} from 'react-router-dom'; function Nav(){ return ( <div> <Link to='/'> Home </Link> <Link to='/about'> About </Link> </div> ); } export default Nav;
NavLink
- <Link>와 거의 동일한 기능을 하지만, 현재 라우트 경로와 일치 여부를 판단하여 스타일 혹은 클래스를 추가할 수 있게 해준다
- ex) 네비게이션 바 구현 시, 현재 선택된 메뉴에 특수한 스타일을 주기 위해 사용한다.
<NavLink to="/about" style={({ isActive }) => ({ fontWeight: isActive ? "bold" : "normal", textDecoration: isActive ? "underline" : "none", })} > 어바웃 </NavLink>
NavLink를 좀 사용해봐야겠다!!
일단 내 기존 네비게이션 바 코드
import React from "react"; import { Link, useLocation } from "react-router-dom"; const Menu: React.FC = () => { const location = useLocation(); // 현재 경로 확인 // 현재 위치 메뉴 색상 const realPriceStyle = location.pathname.startsWith("/realprice_map") && "text-primary-1 "; const charterStyle = location.pathname.startsWith("/charters") && !location.pathname.startsWith("/charters/college") && "text-primary-1 "; const boardStyle = location.pathname.startsWith("/board") && "text-primary-1 "; const dormitoryStyle = (location.pathname.startsWith("/dormitory") || location.pathname.startsWith("/charters/college")) && "text-primary-1 "; return ( <div className="hidden xl:flex pt-0.5"> <Link to="/realprice_map"> <div className={`mx-4 cursor-pointer hover:text-primary ${realPriceStyle}`} > 실거래가 조회 </div> </Link> <Link to="/charters"> <div className={`mx-4 cursor-pointer hover:text-primary ${charterStyle}`} > 월세/전세가 조회 </div> </Link> <Link to="/dormitory"> <div className={`mx-4 cursor-pointer hover:text-primary ${dormitoryStyle}`} > 기숙사와 비교하기 </div> </Link> <Link to="/board"> <div className={`mx-4 cursor-pointer hover:text-primary ${boardStyle}`}> 공지사항 </div> </Link> </div> ); }; export default Menu;
NavLink를 사용하니 이렇게나 간단하게 바꿀 수 있었다고 한다...
import { NavLink } from "react-router-dom"; const Menu = () => { return ( <> <NavLink to="/realprice_map" className={({ isActive }) => isActive ? "cursor-pointer text-primary-1" : "cursor-pointer hover:text-primary" } > 실거래가 조회 </NavLink> <NavLink to="/charters" className={({ isActive }) => isActive ? "cursor-pointer text-primary-1" : "cursor-pointer hover:text-primary" } > 월세/전세가 조회 </NavLink> <NavLink to="/dormitory" className={({ isActive }) => isActive ? "cursor-pointer text-primary-1" : "cursor-pointer hover:text-primary" } > 기숙사와 비교하기 </NavLink> <NavLink to="/board" className={({ isActive }) => isActive ? "cursor-pointer text-primary-1" : "cursor-pointer hover:text-primary" } > 공지사항 </NavLink> </> ); }; export default Menu;
'웹 프로그래밍' 카테고리의 다른 글
useMemo() (0) 2024.11.20 [Vue.js] Computed Properties (0) 2024.11.06 [Vue.js] 시작하기 (0) 2024.11.05 useRef (scrollIntoView) (0) 2024.11.04 TypeScript SVG 파일 (0) 2024.09.20