관리 메뉴

Silver Library (Archived)

useParams, 그리고 react-router-dom 본문

Face the fear, build the future/Revision Sector

useParams, 그리고 react-router-dom

Chesed Kim 2022. 11. 11. 18:20
반응형
// 예시
import { useParams } from "react-router-dom";

function Alpha() {
	const { id } = useParams();
    const package = AlphaList[id];
    return (
    	<div className="package">
      		<h1>{package.name}</h1>
      		<img src={package.image} alt="thumbnail" className="thumbNailSize" />
        	<p>
            	<b>Main Stacks:</b> <br />
                {package.skills}
      		</p>   
            ...
    );
}

아마 react-router-dom 으로 해본 것들은 이런 식으로 정리 해 나가지 않을까 싶네요.

다른 분들이 더 잘 적어 두었을테니 이번에도 나만의 공책이란 느낌으로 적어보고자 합니다.

 

useParams() hook 이란 뭘까요?

일단 이건 react-router-dom 에서 지원되는 건데, 주 기능은 아래와 같습니다.

 

주 기능.

parameter(매게변수) 의 정보를 가져와서 활용하려는 경우.

The useParams hook returns an object of key/value pairs of the dynamic params from the current URL that were matched by the <Route path>. Child routes inherit all params from their parent routes.

 

예시와 적용 사례.

사용 예시는 아래와 같습니다.

아래에서 눈여겨 볼 만한건, ProfilePage function 부분인데요.

그리고<Routes> -> <Route> 내에서, 어떻게 달라지는지. 볼 수 있습니다.

 

그렇다면 이렇게 해 볼 수 있습니다. 이 쯤에서 이 링크를 한번 참고해보는게 좋습니다.

 

[React] useParams() 사용하여 파라미터 가져오기

리액트에서 라우터 사용 시 파라미터 정보를 가져와 활용하고 싶다면 useParams()라는 훅을 사용하면 된다. 라우터를 사용하고 있다는 가정 하에 useParams 사용 방법에 대해 알아보도록 하겠다.1) useP

velog.io

import * as React from 'react';
import { Routes, Route, useParams } from 'react-router-dom';

function ProfilePage() {
  // Get the userId param from the URL.
  let { userId } = useParams();
  // ...
}

function App() {
  return (
    <Routes>
      <Route path="users">
        <Route path=":userId" element={<ProfilePage />} />
        <Route path="me" element={...} />
      </Route>
    </Routes>
  );
}

혹시라도 다른 사용법이 있나 싶어 알아 봤지만, 당장으로서는 의도한 대로 다음과 같습니다.

The useParams() hook is a React Router hook that allows you to access the parameters of the current URL. This can be useful if you want to dynamically render content based on the URL parameters. For example, if you have a blog application, you may want to render different articles based on the article ID in the URL.

설명을 찾아봐도 정말 딱 이런 용도로 쓰이게 될 거라는 걸 암시하고 있는 hook 였습니다.