[REACT] useLoaction

백우진·2022년 12월 10일
0
post-thumbnail

useLocation을 이용해서 현재 페이지의 URL을 가져올 수 있다.

사용법

  1. npm install react-router-dom 설치
  2. useLocation을 import
import { useLocation } from 'react-router-dom';
  1. 변수에 useLocation의 정보를 담는다
const location = useLocation();
  1. console에 출력해보고, 원하는대로 사용하자
const location = useLocation();

useEffect(() => {
  console.log(location);
}, [location])

프로젝트 적용 - 상단바

# styled-componet 부분

const StyledNavbar = styled(Navbar)`
    background-color : ${props => props.pathname === '/' || props.pathname === '/login' || props.pathname === '/Signin' ? 'rgb(37 37 37 / 5%)' : 'white'};
`

# 선언

function Navs() {

    const pathname = useLocation().pathname

    }

    return (
        <StyledNavbar pathname={pathname} collapseOnSelect expand="lg" variant={pathname==='/' || pathname==='/login' || pathname==='/Signin' ? 'dark':'light'} >
      
  • useLocation의 pathname을 가져와서 pathname이라는 변수에 저장
  • StyledNavbar에 props로 pathname을 전달
  • 조건에 따라 다른 디자인이 보여 질 수 있도록 구현

메인화면
대시보드

profile
안녕하세요.

0개의 댓글

관련 채용 정보