본문 바로가기
React (old ver)/basic

React Router 리액트 라우터 활용편 - 상세페이지 제작 Quiz

by by-choice 2021. 11. 6.
반응형

Q. 아래 코드를 변경하여, 각 컴포넌트 아이템(여행 상품)을 클릭하였을 때, 데이터 Id값을 path값으로 지닌 detail 페이지로 넘어가 보자. (예: /Detail/1~3)

export default [
    {
        id: 1,
        country : "Africa",
        city : "Sahara",
        price : "4,500,000"
    },
    {
        id: 2,
        country : "Italy",
        city : "Venice",
        price : "2,000,000"
    },
    {
        id: 3,
        country : "Turkey",
        city : "Cappadocia",
        price : "3,560,000"
    }
]
import { useState } from 'react';
import './App.css';
import itemList from './data';
import Item from './Item.js';
import Detail from './Detail.js';
import { Link, Route, Switch } from 'react-router-dom';

function App() {
  let [items, itemsFunc] = useState(itemList);
  return (
    <div className="App">
      <Route exact path="/">
        <div className="container">
          <div className="row">
            {
              items.map(function( item, i ){
                return (
                  <Item item={ items[i] } i={i} key={i} />
                )
              })
            }
          </div>
        </div>
      </Route>
      <Route path="/detail/경로">
        <Detail item={ items[경로에 맞는 아이템] }></Detail>
      </Route>
    </div>
  );
}

export default App;
import React from "react";

function Item(props){
    return (
        <div className="col-md-5">
            <img src={"images/img"+ (props.i + 1) +".jpg"} width="100%" height="" />
            <h3>{ props.item.country }, { props.item.city }</h3>
            <p>{ props.item.price } won</p>
        </div>
    )
}

export default Item;
import React from "react";

function Detail(props){
    const imgUrl = "../images/img"+ props.item[item위치].id +".jpg"
    return (
        <div className="container">
            <div className="row">
                <div className="col-md-6">
                    <img src={ imgUrl } width="100%" />
                </div>
                <div className="col-md-6 mt-3">
                    <div className="alert alert-danger">The maximum number of guests is 2 guests. </div>
                    <h4>{ props.item[item위치].country }, { props.item[item위치].city }</h4>
                    <h5 className="mb-3"><b>{ props.item[item위치].price }</b> won</h5>
                    <button className="btn btn-dark">Reservation</button> 
                    <button className="btn btn-secondary">Back to main</button> 
                </div>
            </div>
        </div> 
    )
}

export default Detail;
반응형

댓글