[react] 쇼핑몰 project - 4 : react router dom 사용, :id 파라미터 이용

YS_Study.log·2022년 4월 4일
0

영상에서는 전 버전으로 하지만 v6으로 할 예정이다.

React Router Dom 다운

  • 현재 버전 다운 받는 코드

    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

React Router Dom 기본 셋팅

  • index.js 파일에 작성
    - import { BrowserRouter } from "react-router-dom";
    - BrowserRouter 태그로 App 컴포넌트를 감싼다.
// index.js

import { BrowserRouter } from "react-router-dom";

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);
  • Route : Route path="해당경로" url 링크, 해당경로로 접속하면? route태그로 감싼 html 또는 컴포넌트가 보여지게 한다.
  • exact 옵션 : 안쓰면? "/" 링크가 겹치게 되므로 동시에 Detail 컴포넌트와 홈이 같이 웹 페이지에 뜬다. 그러므로 기본 "/" 링크 홈은 exact 로 지정해준다.

    http://localhost:3000/
    http://localhost:3000/detail

  • Switch : 기본 적으로 항상 사용하며, Route들을 감싸준다. Route path="경로" Route 끼리 경로가 겹칠 시 가장 위에 경로 하나만 매칭하여 해당 페이지, 컴포넌트를 보여준다.
  • Link : Link to ="Route path한 경로", Link 태그로 감싼 해당 글자 등을 누를 경우 해당 경로에 route 한 페이지, 컴포넌트로 이동한다.

    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 으로 이동한다.

url 파라미터 문법 :id, useParams 훅 사용

디테일 상세 페이지를 구현하는데 해당하는 신발에 따라 상세페이지가 알맞게 뜨게 하고 싶을 경우 파라미터 문법을 사용한다.

// 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,
  },
];
profile
느리지만 조금씩 공부하는 중 입니다. 현재 1년 6개월차 신입입니다 ><!

0개의 댓글

관련 채용 정보