router
router는 react에서 사용되는 라이브러리로 react로 만들어진 단일 페이지 앱(SPA)에서 사용된다.
html상에서 a 태그를 사용해 링크를 거는 것과 비슷하다고 생각된다.
https://reactrouter.com/en/6.14.0
Home v6.14.0
I'm on v5 The migration guide will help you migrate incrementally and keep shipping along the way. Or, do it all in one yolo commit! Either way, we've got you covered to start using the new features right away.
reactrouter.com
yarn add react-router-dom
router 라이브러리를 추가해 준다.
import React from 'react';
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
import Home from './pages/Home';
import About from './pages/About';
import Profile from './pages/Profile';
import Project from './pages/Project';
const App = () => {
return (
<>
<BrowserRouter>
<nav>
<ul>
<li><Link to="/">home</Link></li>
<li><Link to="/about">about</Link></li>
<li><Link to="/profile">profile</Link></li>
<li><Link to="/project">project</Link></li>
</ul>
</nav>
<Routes>
<Route path='/' element={<Home />} />
<Route path='about' element={<About />} />
<Route path='profile' element={<Profile />} />
<Route path='project' element={<Project />} />
</Routes>
</BrowserRouter>
</>
);
};
export default App;
우선 전체를 BrowserRouter 태그로 감싸 준 뒤 화면에 표시될 부분을 Routes로 묶어 준다.
그 뒤에 Route, path를 사용하면 원하는 컴포넌트를 출력할 수 있다.
위에 있는 Link to 태그를 클릭하면 해당 페이지가 주소에 추가되며 출력된다.