라우팅(Routing)
: 요청에 따라 페이지를 이동하는 것React-Router-Dom
: 리액트에서 사용하는 대표적인 Routing 라이브러리
npm install react-router-dom
or
yarn add react-router-dom
<Route path='/' element={<Home />} />
'링크명'
, '링크명:id'
, '*'
등의 다양한 형태 가능)<Link to='링크명'>표시할 내용</Link>
/:id
의 id)의 정보를 출력함 import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "pages/Home";
import Detail from "pages/Detail";
import NotFound from "pages/NotFound";
const Router = () => {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/:id" element={<Detail/>} />
<Route path="*" element={<NotFound/>} />
</Routes>
</BrowserRouter>
);
};
export default Router;
import Router from "shared/Router";
function App() {
return <Router />;
}
export default App;
import { useNavigate } from "react-router-dom";
function Home() {
const navigate = useNavigate();
return (
<ExButton onClick={() => {navigate(`/detail/${id}`)}}></ExButton>
<ExButton onClick={() => {navigate('/details')}}></ExButton>
);
}
import { useLocation, useParams, Link } from "react-router-dom";
function Detail() {
const pageInfo = useLocation();
const paramInfo = useParams();
console.log(`pageInfo => ${pageInfo}`);
console.log(`paramInfo => ${paramInfo}`);
return (
<Link to='/'>메인 페이지로 이동</Link>
);
}
/* 결과 (ex. detail/12345) */
pageInfo => { pathname: '/detail/12345`, search: '', hash: '', state: null, key: 'default' }
paramInfo => { id: '12345' }