반응형
프로젝트를 만들던 도중 내용만 다르고 똑같은 페이지를 여러 개를 보여줘야 하는데 이때 유용하게 사용할 수 있는 :URL 파라미터에 대해서 알아보겠습니다.
📌언제 사용하기에 적당한가?
1. 한 페이지에서 내용만 달라지고 비슷한 의미를 전달하는 페이지가 여러 개 일 때
2. 페이지가 너무 많을 때
📌어떻게 사용할 수 있는가?
// Detail-data.js
let data = [
{
id: 0,
url: '/share-application/one-serving/0',
img: '/public-assets/one-serving/ramen.jpg',
img_alt: 'ramen',
kind: '라면',
name: '차슈라면 만들어주세요',
content: '차슈라면이 너무 먹고싶어요.. 혹시 차슈라면 할 수 있는 분',
location: '성수동',
author: '미미',
user_img: '/public-assets/one-content/img1.png'
},
{
id: 1,
url: '/share-application/one-serving/1',
img: '/public-assets/one-serving/stew.jpg',
img_alt: 'stew',
kind: '찌개',
name: '된장찌개!',
content: '집밥이 너무 그리워서 된장찌개를 너무 먹고싶어요.',
location: '행당동',
author: '나라',
user_img: '/public-assets/one-content/img2.png'
},
{
id: 2,
url: '/share-application/one-serving/2',
img: '/public-assets/one-serving/noodle.jpg',
img_alt: 'noodle',
kind: '국수',
name: '잔치국수 먹고싶어요',
content: '불어도 괜찮습니다! 전 다 잘 먹어요. 부탁드려요.',
location: '성수동',
author: '국수킬러',
user_img: '/public-assets/one-content/img3.png'
}
];
export default data;
// Detail에 관련된 데이터가 저장된 파일
import data from './Detail-data.js';
import { Routes, Route } from 'react-router-dom';
function App() {
return(
<Routes>
<Route path="/detail/:id" element={<Detail data={data} />}/>
</Routes>
);
}
:id는 여기에 어떤 값이 와도 <Detail />을 보여줍니다.
이렇게 여러 개 컴포넌트를 만들어야 하는 수고를 덜어줍니다.
이제 useParams()로 상세페이지를 만들어보도록 하겠습니다.
📌무슨 역할을 하는 함수인가?
useParams()는 :URL 파라미터의 값을 가져오는 역할을 합니다.
📌어떻게 사용할 수 있는가?
// useParams를 사용하기 위해 import를 해줍니다.
import { useParams } from 'react-router-dom';
function Detail(props) {
// 이렇게 :id 값을 가져옵니다.
let {id} = useParams();
let data = props.data;
return(
<div>
<div className={cn(style.imgContainer)}>
<img src={data[id].img} alt={data[id].img_alt} />
</div>
<article className={cn(style.userContainer)}>
<div className={cn(style.flex)}>
<div className={cn(style.userProfile)}>
<img src={data[id].user_img} alt="user profile" />
</div>
<div className={cn(style.userInfo)}>
<h2>{data[id].author}</h2>
<span>{data[id].location}</span>
</div>
</div>
<div className={cn(style.userManner)}>
<img src="/public-assets/one-content/manner.png" alt="안심온도" />
</div>
</article>
<article className={cn(style.content)}>
<h1>{data[id].name}</h1>
<p>{data[id].content}</p>
</article>
</div>
);
}
/datail/0 이라는 URL로 입력되었으면 useParams()는 0을 반환해줍니다.
그래서 data[0]의 상세 정보들을 가져와서 보여줍니다.
결과
여기서 원하는 글을 클릭하면 아래와 같은 페이지가 나오게 됩니다.
URL에는 /share-application/one-serving/:id 로 만들어서 :id에는 0이 들어가 있습니다.
그래서 Detail-data에서 0번째 데이터를 가져오게 됩니다.
728x90
'React JS' 카테고리의 다른 글
Cannot update a component while rendering a different component 해결하기 (0) | 2023.01.01 |
---|---|
관련된 것 끼리 묶어서 보여주기 (useState 사용) (0) | 2022.12.23 |
메뉴 클릭하면 색상 변경하기 (0) | 2022.12.13 |
클래스명 충돌 css-module로 해결하기 (0) | 2022.12.12 |
드랍 다운 메뉴 만들기 (0) | 2022.12.09 |