개발공부일지
React - react router dom 본문
목차
1. react router dom
2. BrowserRouter
3. Routes, Route
4. Link
1. react router dom
- 설치하기
npm install react-router-dom@6
2. BrowserRouter
// index.js
import { BrowserRouter } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
3. Routes, Route
- 위치가 변경될때마다 <Routes>의 하위경로를 찾아 일치하는 항목을 랜더링해준다.
// app.js
import { Routes, Route } from "react-router-dom";
import Main from "./page/Main";
function App() {
return (
<div className="App">
<Routes>
<Route path="/" element={<Main />} />
</Routes>
</div>
);
}
export default App;
4. Link
- <a href> 와 같은 기능
import React from "react";
import { Link } from "react-router-dom";
const Main = () => {
return (
<div>
Main
<Link to={"/game"}>지뢰찾기</Link>
<Link to={"/game2"}>가위바위보</Link>
</div>
);
};
export default Main;
※ react router 공식사이트
https://reactrouter.com/en/main/start/concepts
const root = ReactDOM.createRoot(
document.getElementById("root")
);
root.render(
<BrowserRouter>
<Routes>
<Route path="/" element={<App />}>
<Route index element={<Home />} />
<Route path="teams" element={<Teams />}>
<Route path=":teamId" element={<Team />} />
<Route path="new" element={<NewTeamForm />} />
<Route index element={<LeagueStandings />} />
</Route>
</Route>
<Route element={<PageLayout />}>
<Route path="/privacy" element={<Privacy />} />
<Route path="/tos" element={<Tos />} />
</Route>
<Route path="contact-us" element={<Contact />} />
</Routes>
</BrowserRouter>
);
'React' 카테고리의 다른 글
React - learn - Reacting to Input with State (input box 사용해보기) (0) | 2023.11.29 |
---|---|
React - learn - Passing Props to a Component (컴포넌트에 props 전달하기) (0) | 2023.11.28 |
React - Tutorial : Tic-Tac-Toe (0) | 2023.11.24 |
React - class component, function component (0) | 2023.11.24 |
React - babel, webpack, react 설치, npm ERR! (1) | 2023.11.23 |