Silver Library (Archived)
useParams, 그리고 react-router-dom 본문
useParams, 그리고 react-router-dom
Ayin 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>
);
}
혹시라도 다른 사용법이 있나 싶어 알아 봤지만, 당장으로서는 의도한 대로 다음과 같습니다.
설명을 찾아봐도 정말 딱 이런 용도로 쓰이게 될 거라는 걸 암시하고 있는 hook 였습니다.
'Face the fear, build the future > Revision Sector' 카테고리의 다른 글
Check out for the fundamentals of CS (0) | 2022.11.27 |
---|---|
useLocation, react-router-dom (0) | 2022.11.11 |
[JS] callback 과 promises, 그리고 API? (0) | 2022.10.20 |
크게 2가지로 나누게 된 개념 - api 와 map function (0) | 2022.10.19 |
[Story] Why Nodejs? (0) | 2022.07.30 |