React Router는 Client Side Router이다.
React Router 공식 홈페이지에서 말하는 세가지 주요 기능이 있는데 이는 아래와 같다.
- Subscribing and manipulating the history stack
- Matching the url to your routes
- Rendering a nested UI from the route matches
React Router 공식 홈페이지에 들어가면 위와 같이 설명되어 있는데 이를 풀어보면 다음과 같다.
예를 들어보자.
위처럼 해당 경로에 들어가고 나가는 동작 모두가 History Stack이라는 공간에 남게되고, 이를 조작하여 url을 추적, 이동할 수 있게 된다.
이로 인해 내가 원하는 경로의 url로 이동 및 뒤로가기, 앞으로가기 기능을 활용할 수 있는 것이다.
자, 그럼 history Stack이 무엇인지 얼추 느낌이 왔을 것이다.
그렇다면 React Router에서는 history를 어떻게 조작할 수 있는지 보자.
import * as React from "react";
import { Routes, Route, Outlet, Link } from "react-router-dom";
export default function App() {
const history = createBrowserHistory();
return (
<div>
<h1>Basic Example</h1>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="about" element={<About />} />
</Route>
</Routes>
</div>
);
}
위 코드를 한번 보자.
(history는 크게 세가지가 있으나 여기에서는 browser history를 예시로 한다.)
위 코드에서 createBrowserHistory 함수를 통해 history를 생성함을 볼 수 있다.
import * as React from "react";
import { BrouserRouter, Route, Outlet, Link } from "react-router-dom";
export default function App() {
return (
<div>
<h1>Basic Example</h1>
<BrouserRouter>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="about" element={<About />} />
</Route>
</BrouserRouter>
</div>
);
}
이처럼 BrouserRouter 객체로 감싸게 되면 defaultProps에 자동으로 history 객체가 들어가게 된다.
history 객체에 back, forward, go등 브라우저 뒤로가기, 앞으로가기등의 기능이 구현된 것을 볼 수 있다.
(페이지 이동은 history.push(url)이렇게 이동한다.)
해당 history객체를 전달하여 각 Component에서 불러와서 사용할 수 있는 것이다.
<페이지 이동 예제>
import React from 'react';
import { withRouter } from 'react-router-dom';
const Home = ({history}) => {
return (
<button onClick = {() => {history.push('/About')}}>
To About
</button>
);
}
export default withRouter(Home); //반드시 이렇게 감싸주어야 history 객체를 사용할 수 있다.
import React from 'react';
import { useHistory } from 'react-router-dom';
const Home = () => {
const history = useHistory();
return (
<button onClick={() => history.push('/About')}>
To About
</button>
);
};
export default Home;
import React from 'react';
import { useNavigate } from 'react-router-dom'; //V6
const Home = () => {
const navigate = useNavigate();
return (
<button onClick={() => navigate('/About')}>
To About
</button>
);
};
export default Home;
import React from 'react';
import { useLocation } from 'react-router-dom';
import queryString from 'query-string';
const Home = () => {
const { search } = useLocation();
const { params } = queryString.parse(search);
return (
<div>
{params}
</div>
);
}
export default Home;
2편에서 계속...
부족한 글 봐주셔서 감사합니다.
피드백, 지적은 항상 감사합니다.