[ react - router - dom 사용방법 ] quick-guide
router? 화면(페이지)를 전환하는 것
ex) http://localhost:3000 -> http://localhost:3000/movies/123123
이동을 도와주는 것
1. npm i react-router-dom@5.3.0 설치
ver.5 -> ver.6 변경사항
1) Switch컴포넌트 -> Routes 컴포넌트로 변경
2) Route 컴포넌트 사이에 자식 컴포넌트 -> element prop에 자식 컴포넌트 할당 변경
ver.6 관련문서
2. import 하기
import {
BrowserRouter as Router,
Switch,
Router,
Link
} from "react-router-dom";
# Hash Router 와 Browser Router (2가지 형태의 라우터)
- Browser Router: 기본적인 웹사이트 형식 ---> http://localhost:3000/movies/123123
- Hash Router: 중간에 #이 붙는 형식 ---> http://localhost:3000/#/movies/123123
# Link: 브라우저 새로고침 없이 다른 페이지로 이동시켜주는 컴포넌트 <a> 태그는 브라우저 전체를 새로고침하여 이동한다.
3. 컴포넌트하기
- Switch: Router를 찾는 일 (movies/123123)해당하는 부분을 찾으면 렌더링
<Router> <Switch> // 한 번에 하나의 Route만 찾아 레더링하기 위해서 (원하면 2개의 Route를 한번에 레더링할 수 있다) <Route path="/movie"> </Route> 디테일화면 <Route path="/"> </Route> 홈화면 </Switch> </Router> |
- Link: 새로고침 하지않고 브라우저 이동, 빠르게 반응
import {Link} from "react-router-dom" <h2> <Link to="/movie"> {title} </Link> </h2> |
<코드>
더보기
<App.js>
import {
BrowserRouter as Router,
Routes,
Route,
} from "react-router-dom";
import Detail from "./routes/Detail";
import Home from "./routes/Home";
function App() {
return (
<Router>
<Routes>
<Route path="/movie" element={ <Detail />}> </Route>
<Route path="/" element={<Home />}> </Route>
</Routes>
</Router>
)
}
export default App;
<Movie.js>
import PropTypes from "prop-types";
import {Link} from "react-router-dom"
function Movie({ coverImg, title, summary, genres }) {
return <div>
<img src={coverImg} alt={title} />
<h2> <Link to="/movie">{title}</Link> </h2>
<p>{summary}</p>
<ul>
{genres.map((g) => (
<li key={g}>{g}</li>
))}
</ul>
</div>;
}
// Movie.PropTypes = {
// coverImg: PropTypes.string.isRequired,
// title: PropTypes.string.isRequired,
// summary: PropTypes.string.isRequired,
// genres: PropTypes.arrayOf(PropTypes.string).isRequired,
// };
export default Movie;
반응형
'프론트엔드 > react' 카테고리의 다른 글
| React (12) - router 사용방법 #2 (0) | 2023.04.28 |
|---|---|
| React (11) - API #2 컴포넌트 활용하기 (0) | 2023.04.28 |
| React (11) - API #1 await (0) | 2023.04.27 |
| React (10) - USDtoCOIN Converter, API (0) | 2023.04.27 |
| React(9) - ToDoList 만들기 (0) | 2023.04.25 |