location.hash
location 인터페이스 (BOM 메서드)
hash는 URL decoded되지 않고 만일 hash가 없다면 이 프로퍼티는 empty string이 될 것.
// location: https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container
const loc = document.location;
console.log(loc.href); // https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container
console.log(loc.protocol); // https:
console.log(loc.host); // developer.mozilla.org:8080
console.log(loc.hostname); // developer.mozilla.org
console.log(loc.port); // 8080
console.log(loc.pathname); // /en-US/search
console.log(loc.search); // ?q=URL
console.log(loc.hash); // #search-results-close-container
console.log(loc.origin); // https://developer.mozilla.org:8080
location.assign("http://another.site"); // load another page
history
HIstory API의 인터페이스인 history는 browser session history의 조작을 허용한다.
// Should be null because we haven't modified the history stack yet
console.log("History.state before pushState: ", history.state);
// Now push something on the stack
history.pushState({ name: "Example" }, "pushState example", "page3.html");
// Now state has a value.
console.log("History.state after pushState: ", history.state);
Fragment 해시
hash변경이 일어났을 때 브라우저는 서버에 요청하지 않고 페이지가 새로고침 되지 않음
라우터의 기본 기능
애플리케이션 경로목록 저장
URL이 변경되면 페이지 콘텐츠를 해당 구성요소로 교체
URL에서 path parameter나 query string을 식별가능
궁금한점
리액트 라우터는 location.pathname에 설정되는 것인가?
js로 레이아웃을 설정하려면? (defaultLayout)
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Routes, Route, Link, useParams, Navigate } from 'react-router-dom';
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
function User() {
const { id } = useParams();
return <h2>User ID: {id}</h2>;
}
function ProtectedRoute({ children }) {
const isAuthenticated = false; // 인증 여부 확인 로직
if (!isAuthenticated) {
return <Navigate to="/" />;
}
return children;
}
function Navigation() {
return (
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/user/1">User 1</Link></li>
<li><Link to="/protected">Protected</Link></li>
</ul>
</nav>
);
}
function App() {
return (
<Router>
<Navigation />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/user/:id" element={<User />} />
<Route
path="/protected"
element={
<ProtectedRoute>
<h2>Protected Page</h2>
</ProtectedRoute>
}
/>
</Routes>
</Router>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
'TIL' 카테고리의 다른 글
createRoot (0) | 2024.12.16 |
---|---|
TIL pub sub 패턴 (0) | 2024.06.23 |
TIL 시맨틱, XMLHttpRequest, 이벤트 위임 제약 (0) | 2024.06.22 |
웹 서비스를 제공하는 방식 (0) | 2024.06.19 |
결합도와 응집도 (0) | 2024.06.18 |