다이나믹 라우팅이란?
- 여기서 말하는 다이나믹 라우팅이란 다음과 같다.
- http://localhost:3000/profile - 이런 방식의 라우팅만 커버하고 있지만
- http://localhost:3000/profile/1 - 원래 있던 라우팅 되는 path 뒤에 또 다른 값이 붙었을 때 처리하는 방식을 말한다.
Dynamic Routing by ID
import { BrowserRouter, Route } from "react-router-dom";
import About from "./pages/About";
import Home from "./pages/Home";
import Profile from "./pages/Profile";
function App() {
return (
<BrowserRouter>
<Route path="/" exact component={Home} />
<Route path="/profile" exact component={Profile} />
<Route path="/profile:id" component={Profile} />/*새로 추가된 코드*/
<Route path="/about" ecomponent={About} />
</BrowserRouter>
);
}
export default App;
- 다음과 같이 Profile path 코드를 한 줄 복사 해준 뒤 뒤에 :(colon)id를 붙여 만들어 주었다.
//profile.jsx
export default function Profile(props) {
console.log(props)
return <div>Profile 페이지 입니다.</div>;
}
- console.log로 들어오는 props를 확인해보면 다음과 같은 데이터가 props 인자로 넘어오는 것을 알 수 있다. Profile이라는 컴포넌트가 Route의 컴포넌트로 연결되었다는 것을 알 수 있다.
- Route 컴포넌트를 통해 Profile의 props에 데이터가 주입된다.
- props로 주입된 match에 params의 객체데이터인 id를 가져오면 id 값을 받을 수 있을 것이다.
export default function Profile(props) {
const id = props.match.params.id;
console.log(id, typeof id);
return <div>Profile 페이지 입니다.</div>;
}
- id 값과 그 id의 값이 string임을 알 수가 있다.
export default function Profile(props) {
const id = props.match.params.id;
console.log(id, typeof id);
return (
<div>
<h2>Profile 페이지입니다.</h2>
{id && <p>id 는 {id} 입니다.</p>}
</div>
);
}
- 다음과 같이 작성하면 id의 값을 html내에 표시 할 수 있을 것이다.
- { id && } 는 조건부 렌더링 역할을 하는 것으로 id 값이 null이 아니면 출력해주는 것이다. 즉, 일반적인 /profile로 들어온 것이 아닌 /profile/id라는 url로 client side에서 접속했을 때 알려 주는 것이다.
Dynamic Routing by Key Value
- http://localhost:3000/profile/1 - 방금 봐 왔던 id 방식이 아닌, key value는 다음과 같은 방식으로 작성 한다.
- http://localhost:3000/about?name=mark - ?를 사용하여 key와 value 값을 가져다준다.
- 다음과 같은 형식은 QueryString이라고도 부른다.
- 또한 해당 값은 optional이기 때문에 있을 수도 있고 없을 수도 있는 값이다.
props를 console.log로 찍고 해당 url에서 props 값을 알아보자.
- search라고 하는 항목에 ?name=mark를 준다. 이 값을 꺼내서 사용할 수 있는 방법이 총 2가지가 있다.
1. URLSearchParams를 사용하여 값들을 사용하기
export default function About(props) {
const searchParams = new URLSearchParams(props.location.search);
const name = searchParams.get('name');
console.log(name);
return (
<div>
<h2>About 페이지 입니다.</h2>
{name && <p>name 은 {name} 입니다.</p>}
</div>
);
}
2. query-string 패키지 사용하기
https://www.npmjs.com/package/query-string
import queryString from 'query-string';
export default function About(props) {
const query = queryString.parse(props.location.search);
const { name } = query;
console.log(name);
return (
<div>
<h2>About 페이지 입니다.</h2>
{name && <p>name 은 {name} 입니다.</p>}
</div>
);
}
레퍼런스
'프론트엔드 개발 > React' 카테고리의 다른 글
[React] Styled Components (0) | 2022.07.06 |
---|---|
[React] Router - JSX로 라우팅 이동하기 (0) | 2022.07.05 |
[React] SPA Router (0) | 2022.07.05 |
[React] Component (0) | 2022.07.04 |
[React] SSR vs. CSR (Feat.Next.js) (0) | 2022.07.01 |