영상에서는 전 버전으로 하지만 v6으로 할 예정이다.
yarn add react-router-dom
npm i react-router-dom
npm install react-router-dom@5.2.0
yarn add react-router-dom@5.2.0
// index.js
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById("root")
);
HOME 글씨 클릭 === http://localhost:3000/ 같은 것
<Switch>
// http://localhost:3000/ => Home 으로 이동
<Route exact path="/">
...Home 관련 html
</Route>
// http://localhost:3000/detail => Detail 컴포넌트로 이동
<Route path="/detail">
<Detail />
</Route>
</Switch>
....
<Link to="/">Home</Link>
// Home 글자를 클릭 할 경우? Route exact path="/" 와 동일한 ...Home 관련 html 으로 이동한다.
디테일 상세 페이지를 구현하는데 해당하는 신발에 따라 상세페이지가 알맞게 뜨게 하고 싶을 경우 파라미터 문법을 사용한다.
http://localhost:3000/detail/1 검색=> 1번 신발 디테일 컴포넌트
http://localhost:3000/detail/2
http://localhost:3000/detail/3
// App.js 파일
// <Route path="/detail">
<Route path="/detail/:id">
<Detail />
</Route>
data.js 내의 신발의 고유한 id를 사용하여 url 경로 파라미터 id와 같은 경우를 찾아 변수 findShoes에 담아준다.
=> 이유 home 의 신발정렬이 항상 똑같을 수는 없다, 예를 들어 가격순, 인기순, 최신순으로 정렬할때마다 신발 정렬번호는 바뀔 것이기에 신발 디테일 id 번호는 신발의 원래 고유한 id가 같은 경우 detail 상세 페이지를 보여줘야하기 때문이다.
Detail.js 컴포넌트
...
import { useHistory, useParams } from "react-router-dom";
function Detail({ shoes }) {
let { id } = useParams();
let findShoes = shoes.find(function (product) {
return product.id === id;
});
...
return (
<div className="container">
<div className="row">
<div className="col-md-6">
<img
src={`https://codingapple1.github.io/shop/shoes${
findShoes.id + 1
}.jpg`} width="100%"/>
</div>
<div className="col-md-6 mt-4">
// <h4 className="pt-5"> {shoes[id].title}</h4>
//<p>{shoes[id].content}</p>
//<p>{sshoes[id].price}</p>
<h4 className="pt-5">{findShoes.title}</h4>
<p>{findShoes.content}</p>
<p>{findShoes.price}원</p>
....
</div>
</div>
</div>
);
}
export default Detail;
export default [
{
id: 0,
title: "Hansome",
content: "누구보다 멋지고 싶은 날 꾸며주는 신발",
price: 100000,
},
{
id: 1,
title: "cute",
content: "가볍고 운동하기 좋은 신발",
price: 80000,
},
{
id: 2,
title: "nice",
content: "발목까지 감싸주는 신발",
price: 110000,
},
];