npm install react-router-dom
import { BrowserRouter, Routes, Route, Link, useLocation, useParams }
from "react-router-dom";
function App() {
return (
<BrowserRouter>
<Link to="/"> home </Link>
<Link to="/one"> one </Link>
<Link to="/two"> two </Link>
<Link to="/three"> three </Link>
<Link to="/blog/1"> four_1 </Link>
<Link to="/blog/2"> four_2 </Link>
<Link to="/blog/3"> four_3 </Link>
<Routes>
<Route path="/" element={<Index />}/>
<Route path="/one" element={<One name='licat' />}/>
<Route path="/two" element={<Two />}/>
<Route path="/three" element={<Three />}/>
<Route path="/blog/:id" element={<Blog />}/>
</Routes>
</BrowserRouter>
);
}
function Blog(){
const location = useLocation(); //현재 url정보
//console.log(location)
//{pathname: '/blog/1', search: '', hash: '', state: null, key: 'm2qu9n'}
const path = location.pathname.split('/')[2]
// '/blog/1'.split('/')
// ['','blog','1']
//console.log(path)
// <Link to="/blog/1"> four_1 </Link>을 클릭시 path는 1
const param = useParams();
//console.log(param)
// {id: '1'}
return <h1>hello Blog^0^ this is blog page {path}</h1>
}
export default App;
RouteSolve.jsx
function RouteSolve() {
const productIds = [1,2,3,4,5]
return (
<BrowserRouter>
<h1>퀴즈</h1>
<Link to="/"> 홈페이지 </Link> <br/>
{productIds.map((productId) => (
<>
<Link to={`/products/${productId}`}>상품{productId}</Link><br/>
</>
))}
<Link to="/users"> Users </Link><br/>
<Link to="/cart"> Cart </Link>
<Routes>
<Route path="/" element={<HomePage />}/>
<Route path="/products/:id" element={<Products />}/>
<Route path="/products/:id/notice" element={<ProductNotice />}/>
<Route path="/cart" element={<Cart name='licat' />}/>
<Route path="/users/" element={<Users />}>
<Route path="coupon" element={<div>쿠폰</div>}/>
<Route path="question" element={<div>퀘스션</div>}/>
<Route path="notice" element={<div>노티스</div>}/>
</Route>
</Routes>
</BrowserRouter>
);
}
function Users(){
return (
<>
<br/>
<Link to="/users/coupon"> UsersCoupon </Link>
<br/>
<Link to="/users/notice"> UsersNotice </Link>
<br/>
<Link to="/users/question"> UsersQuestion </Link>
<br/>
<h1>여기는 Users</h1>
<Outlet/>
</>
)
}
function Products(){
const {id} = useParams()
return (
<>
<h1>hello Products{id}</h1>
<Link to="./notice">Notice</Link>
{/* ./는 현재경로이다. */}
{/* 성퓸5를 누르면 products/5/notice 이렇게됨 */}
</>
)
}
function ProductNotice(){
const {id} = useParams()
return <h1>hello Products{id} Notice</h1>
}
<Route path='/about' element={<About/>}>
<Route path='member' element={<div>멤버임</div>}/>
<Route path='location' element={<div>로케이션</div>}/>
</Route>
function About(){
return(
<div>
<h4>회사정보임</h4>
<Outlet></Outlet>
</div>
)
}
프론트엔드 스쿨 5월 12일,15일 강의 내용