
// pushState로 /sparrow/1234로 가게되면
history.pushState({ color: 'brown' }, '', '/sparrow/1234')
// 실제로 주소창이 /sparrow/1234로 변경되고
history.state // { color: 'brown'} 출력

window.addEventListener('popstate', (event) => {
console.log(event.state)
})
// 어떤 정보가 주어졌을 때 특정한 페이지를 렌더링
const route = (page) => {
if(page === 12){
someDivElement.textContent = '12쪽입니다.';
}
}
// 주소 바꾸기
someButton.addEventListener('click', () => {
history.pushState({ page: 12 }, '', '/page/12');
route(12)
})
// 저장된 state를 이용해 라우팅
window.addEventListener('popstate', (event) => {
route(event.state.page);
})
history[replace ? 'replaceState', 'pushState'](state, '', url)
export function createBrowserRouter(
routes: RouteObject[],
opts?: DOMRouterOpts
): RemixRouter {
return createRouter({
basename: opts?.basename,
future: opts?.future,
hisotry: createBrowserHistory({ window, opts?.window }),
hydrationData: opts?.hydrationData || parseHydrationData(),
routes,
detectErrorBoundary,
}).initialize();
}
export function createBrowserHistory(
options: BrowserHistoryOptions = {}
): BrowserHistory {
function createBrowserLocation(
window: Window,
globalHistory: Window["history"]
) {
let { pathname, search, hash } = window.location;
return createLocation(
"",
{ pathname, search, hash },
(globalHistory.state && globalHistory.state.usr) || null,
(globalHistory.state && globalHistory.state.key) || "defualt",
)
}
}
// createBrowserHistory의 return 값
return getUrlBasedHistory(
createBrowserLocation,
createBrowserHref,
null,
options
)
function getUrlBasedHistory(
getLocation: (window: Window, globalHistory: Window["history"]) => Location,
createHref: (window: Window, to: To) => string,
vaildateLocation: ((location: Location, to: To) => void) | null,
options: UrlHistoryOptions = {}
): UrlHistory {
// getUrlBasedHistory에 메서드로 push가 있음
function push(to: To, state?: any) {
...
try{
globalHistory.pushState(historyState, "", url);
} catch (error){
...
}
이번 글에서는 History API에 대해서 다뤘습니다. History API는 useCustomBack이라는 커스툼 훅을 개발하는 과정에서 다뤄본적이 있는데요. popstate 이벤트가 발생했을 때 브라우저의 동작을 막고 특정 함수를 실행하는 기능이었습니다. 이렇게 다시 공부해보니까 새롭네요. SPA의 라우팅을 History API를 통해서 구현했다는 부분과 해당 기능을 확인하기 위해서 라이브러리를 분석하는 부분이 너무 좋았습니다.