Parameter, Hooks

choi seung-i·2022년 5월 8일
0

FE로그

목록 보기
12/19
post-thumbnail

Path Parameter

localhost:3000/product/125

<BrowserRouter>
  <Routes>
    <Route path='/product/:id' element={<ProductDetail />} />
  </Routes>
</BrowserRouter>
  • 맨 뒤에 125처럼 url 경로에서 달라지는 부분을 저장하는 매개 변수를 Path Parameter 라고 합니다.
  • Path Parameter 앞에는 :가 붙어야 함
  • :id 의 id는 임의의 값으로 마음대로 네이밍 가능 (ex. :pagename)

Query Parameter

function useQuery() {
  return new URLSearchParams(useLocation().search);
}

function QueryParamsDemo() {
  let query = useQuery();
  
  return (
    <Child name={query.get("name")} />
  )
}

function Child({ name }) {
  //name 가져다가 쓸 수 있음
}
  • 데이터 필터링
  • 무한스크롤, 페이지네이션 적용 가능

Hooks

useNavigate()

const navigate = useNavigate();

const goToDetail = () => {
	navigate(`/product/${id}`);
}

인자에 정수값을 넣으면 방문기록에 남아있는 경로 이동

navigate(-1); // 뒤로 가기
navigate(-2); // 뒤로 2페이지 가기
navigate(1);  // 앞으로 가기

useLocation()

const location = useLocation();
console.log(location);
/// 객체 반환
{
  pathname: '/product/1', 
  search: '', 
  hash: '', 
  state: null, 
  key: 'default'
}
  • pathname : 현재 경로 값
  • search : query parameter 값

useParams() : hooks

<Route path = '/onboarding/:eventId/:groupId/:userId' exact component = {OnboardingViewController} />

const  { eventId,  groupId, userId } = useParams();
// 현재경로: /product/1
<BrowserRouter>
  <Routes>
    <Route path='/product/:productId' element={<ProductDetail />} />
  </Routes>
</BrowserRouter>

const params = useParams();
console.log(params)
//객체 반환
{
  productId: 1
}


공부하며 정리&기록하는 ._. 씅로그

profile
Front-end

0개의 댓글