개발노트

7. [ReactJS] Router 페이지 전환(with useParams) 본문

웹 개발/React.js

7. [ReactJS] Router 페이지 전환(with useParams)

mroh1226 2023. 6. 12. 15:11
반응형

React Router

React v6부터는 문법 변동 사항이 있습니다.

- 참고링크: https://reactrouter.com/en/6.12.1

 

Home v6.12.1

I'm on v5 The migration guide will help you migrate incrementally and keep shipping along the way. Or, do it all in one yolo commit! Either way, we've got you covered to start using the new features right away.

reactrouter.com


React Router 패키지 설치하기.

React Router는 react-router-dom이라는 패키지로 제공되므로, 프로젝트 디렉토리에서 다음 명령어를 사용하여 설치할 수 있습니다:

npm install react-router-dom

위 명령어를 실행하면 프로젝트의 package.json 파일에 react-router-dom 패키지가 추가되고, 해당 패키지와 관련된 의존성이 자동으로 설치됩니다.



Path로 페이지 이동하기을 위한 Router 생성.

import { BrowserRouter as Router, Route, Routes, Link } from "react-router-dom";
import Home from "./routes/Home";
import Detail from "./routes/Detail";
import ToDoList from "./routes/ToDoList";
import CoinTraker from "./routes/CoinTracker";

function App() {
  return (
    <div>
      <Router>
        <RouterBar />
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/movie/:id" element={<Detail />} />
          <Route path="/ToDoList" element={<ToDoList />} />
          <Route path="/CoinTracker" element={<CoinTraker />} />
          <Route path="*" element={<Home />} />
        </Routes>
      </Router>
    </div>
  );
}

function RouterBar(params) {
  return (
    <div>
      <h2>
        <Link to={"/Home/"}>Home</Link>
      </h2>
      <h2>
        <Link to={"/CoinTracker/"}>CoinTracker</Link>
      </h2>
      <h2>
        <Link to={"/ToDoList/"}>ToDoList</Link>
      </h2>
    </div>
  );
}

export default App;
  1. Router 기능을 넣어줄 컴포넌트를 생성해줍니다. (예시로 App() 생성)
  2. <Router>를 return 해주도록 작성합니다.
  3. <Routes> 로 여러 <Route>를 감싸줘 그중 규칙이 일치하는 <Route>를 랜더링 할 수 있도록 만들어줍니다.
  4. <Route>의 path 속성에는 경로를, element 속성에는 컴포넌트를 넣어줍니다.
  5. path="*" 은 정의되지않은 Path로 이동시 라우팅됩니다.

*import { BrowserRouter as Router, Route, Routes, Link } from "react-router-dom"; 
오류가 난다면 위 부분이 맞게 되었는 지 확인해주세요.


useParams로 Parameter 값 받아오기.

 

흐름도

소스코드.

Home.js
import { useEffect, useState } from "react";
import MovieDetail from "../components/MovieDetail";
import "../styles.css";
const url_movie =
  "https://yts.mx/api/v2/list_movies.json?minimum_rating=9&sort_by=year";

function Home() {
  const [loading, setLoading] = useState(true);
  const [movies, setMovies] = useState([]);
  useEffect(() => {
    fetch(url_movie)
      .then((response) => response.json())
      .then((json) => {
        setMovies(json.data.movies);
        setLoading(false);
        console.log(json.data.movies);
      })
      .catch((error) => {
        alert(error);
      });
  }, []);
  return (
    <div className="movieCard">
      <div>
        <h1>Movie List</h1>
        {loading ? (
          <h2>Loading...</h2>
        ) : (
          <div style={{ padding: "20px" }}>
            {movies.map((currentArray) => (
              <MovieDetail
                key={currentArray.id}
                id={currentArray.id}
                medium_cover_image={currentArray.medium_cover_image}
                title={currentArray.title}
                year={currentArray.year}
                runtime={currentArray.runtime}
                genres={currentArray.genres}
                synopsis={currentArray.synopsis}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

export default Home;

 

MovieDetail.js
import { Link } from "react-router-dom";
function MovieDetail({
  medium_cover_image,
  title,
  year,
  runtime,
  genres,
  synopsis,
  id,
}) {
  return (
    <div>
      <img src={medium_cover_image} alt={title} />
      <h2>
        <Link to={`/movie/${id}`}>{title}</Link>
      </h2>
      <span>{year} / </span>
      <span>{runtime}minutes / </span>
      <span>
        {genres.map((g, index) => (
          <p key={index}>{g}</p>
        ))}
      </span>
      <p>{synopsis}</p>
    </div>
  );
}

export default MovieDetail;

 

Detail.js
import { useEffect, useState } from "react";
import { json, useParams } from "react-router-dom";

function Detail() {
  const { id } = useParams();
  return (
    <div>
      <h1>{id}</h1>
    </div>
  );
}

export default Detail;

 

 

라우터 사용 예시

 

※예시 출처:https://nomadcoders.co/

 

노마드 코더 Nomad Coders

코딩은 진짜를 만들어보는거야!. 실제 구현되어 있는 서비스를 한땀 한땀 따라 만들면서 코딩을 배우세요!

nomadcoders.co

 

반응형
Comments