Router에서는 a태그를 사용하면 서버에 새로운 페이지로 연결되어 SPA로 작동하지 못합니다.
그래서 React-Router에서 Link, NavLink 컴포넌트를 제공합니다.
준비 작업
index.js
import React from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { createBrowserRouter, createRoutesFromElements, Route, RouterProvider} from 'react-router-dom';
import Home from './Home';
import Blog from './Blog';
const router = createBrowserRouter(
createRoutesFromElements(
<>
<Route path='/' element={<App></App>}>
<Route path='home' element={<Home></Home>}></Route>
<Route path='blog' element={<Blog></Blog>}></Route>
</Route>
</>
)
)
createRoot(document.getElementById('root')).render(
<RouterProvider router={router}></RouterProvider>
)
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
Link
기존에는 url창에 직접 http://localhost:3000/home 같이 직접 입력했지만,
Link 컴포넌트를 이용하면 a 태그처럼 클릭 한번으로 다른 화면을 출력시킬 수 있습니다.
예제를 한번 만들어 보겠습니다.
App.js
import { Link, Route, Routes } from 'react-router-dom';
import './App.css';
import Blog from './Blog';
import Home from './Home';
function App() {
return (
<div>
<ul>
<li><Link to='/home'>HOME</Link></li>
<li><Link to='/blog'>BLOG</Link></li>
</ul>
<p>APP PAGE 입니다.</p>
<Routes>
<Route path='/home' element={<Home></Home>}></Route>
<Route path='/blog' element={<Blog></Blog>}></Route>
</Routes>
</div>
);
}
export default App;
to는 Route 객체로 만들어둔 경로를 사용합니다.
/ 에 따라 상대경로 절대경로가 설정됩니다.
상대경로 to = 'home' http://localhost:3000/app/home
절대경로 to = '/home' http://localhost:3000/home
to = '..'
상대 경로를 이용해 한단계 높은 Route로 가는 방법
import React from 'react';
import { Link } from 'react-router-dom';
const Blog = () => {
return (
<div>
<Link to='..'>back</Link>
<h1>BLOG</h1>
<p>BLOG PAGE 입니다.</p>
</div>
);
};
export default Blog;
이렇게 설정하면 http://localhost:3000/blog 의 부모인 http://localhost:3000/ 화면이 출력됩니다.
NavLink
Link 컴포넌트와 달리 active 상태를 알 수 있는 NavLink 컴포넌트도 있습니다.
주로 내비게이션 메뉴에서 사용됩니다.
Link 컴포넌트를 NavLink로 변경만 해주면 select에 따라 active 클래스가 추가되는 걸 알 수 있습니다.
App.css를 변경해 조금 더 잘 보이게 만들었습니다.
App.css
a{
text-decoration: none;
color: black;
font-size: 1rem;
}
.active{
font-weight: bold;
font-size: 1.2rem;
}
나머지 자세한 내용은 공식 사이트에서 확인 바랍니다.
https://reactrouter.com/en/main
Home v6.8.1
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
'WEB > HTML CSS JS' 카테고리의 다른 글
리눅스 서버 putty로 접속해서 nodejs, npm, yarn 설치하기 (1) | 2023.02.17 |
---|---|
AutoSet10 사용해서 웹 서버 만들어 index.html 접속하기 (0) | 2023.02.16 |
[React Router v6] 2. Path Segment (0) | 2023.02.11 |
[React Router v6] 1. BrowserRouter (1) | 2023.02.11 |
[Node.js] npm 대신 yarn 설치하기 (0) | 2023.02.06 |