react-router-dom 설치
npm i react-router-dom
Router와 Route
Route는 어떤 component를 어떤 url에 불러올지 결정
Router 아래에 Route를 모아놓음
HashRouter를 사용한 코드
//src/App.js
import React from "react";
import { HashRouter, Route } from "react-router-dom";
import Home from "./routes/Home";
import About from "./routes/About";
import Detail from "./routes/Detail";
import Navigation from "./components/Navigation";
import "./App.css";
function App() {
return (
<HashRouter>
<Navigation />
<Route path="/" exact={true} component={Home} />
<Route path="/about" component={About} />
<Route path="/movie/:id" component={Detail} />
</HashRouter>
);
}
export default App;
exact = {true}
이 path일 때만 component 불러옴
네비게이션, Link
//src/components/Navigation.js
import React from "react";
import { Link } from "react-router-dom";
import "./Navigation.css";
function Navigation() {
return (
<div className="nav">
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</div>
);
}
export default Navigation;
//src/components/Movie.js
import React from "react";
import PropTypes from "prop-types";
import "./Movie.css";
import { Link } from "react-router-dom";
function Movie({ id, year, title, summary, poster, genres }) {
return (
<Link
to={{
pathname: `/movie/${id}`,
state: {
year,
title,
summary,
poster,
genres
}
}}>
<div className="movie">
<img src={poster} alt={title} title={title} />
<div className="movie__data">
<h3 className="movie__title">{title}</h3>
<h5 className="movie__year">{year}</h5>
<ul className="movie__genres">
{genres.map((genre, index) => (
<li key={index} className="genres__genre">
{genre}
</li>
))}
</ul>
<p className="movie__summary">{summary.slice(0, 180)}...</p>
</div>
</div>
</Link>
);
}
Movie.propTypes = {
id: PropTypes.number.isRequired,
year: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
summary: PropTypes.string.isRequired,
poster: PropTypes.string.isRequired,
genres: PropTypes.arrayOf(PropTypes.string).isRequired
};
export default Movie;
참고 | 노마드코더 - ReactJS로 영화 웹 서비스 만들기
'web' 카테고리의 다른 글
[Vue.js] 템플릿 문법 (0) | 2023.09.11 |
---|---|
npx create-react-app 오류 - no longer supported (0) | 2023.08.10 |
내부 IP 주소, 외부 IP 주소 확인하기 - 윈도우 (0) | 2022.03.25 |
VSCode 스크립트 실행 오류 해결 방법 (0) | 2021.08.07 |