#6 ROUTING BONUS

2021. 1. 10. 15:43·💻 Study/웹
728x90

6.0 Getting Ready for the Router

이전에 만든 사이트를 좀 더 interactive하게 해보자.

react-router-dom

npm install react-router-dom

 

components, routes 폴더

js와 css를 옮긴다.

기존 App.js의 내용을 Home.js로 옮긴다. (App -> Home 수정 필요)

About.js는 아직 작성 안 된 상태


6.1 Building the Router

App.js에서 Router 만들기

Router는 url을 가져다가 보고 우리가 라우터에게 명령한 것에 따라 component(page)를 불러온다.

 

import React from "react";
import { HashRouter, Route } from "react-router-dom";
import Home from "./routes/Home";
import About from "./routes/About";

function App(){
  return <HashRouter>
    <Route path="/" component={Home} />
    <Route path="/about" component={About} />
  </HashRouter>
}

export default App;

위 코드로 실행 시, "/about" 의 url에서 Home component와 About component가 둘 다 rendering되는 문제가 발생한다

 

"/"을 Router인 경우, 제대로 안되는 이유

react가 /로 시작하는 url을 모두 render하기 때문

 

그래서!

exact를 사용!

: 이것을 제외하고 나머진 render X

import React from "react";
import { HashRouter, Route } from "react-router-dom";
import Home from "./routes/Home";
import About from "./routes/About";

function App(){
  return <HashRouter>
    <Route path="/" exact={true} component={Home} />
    <Route path="/about" component={About} />
  </HashRouter>
}

export default App;

6.2 Building the Navigation

component들 사이 어떻게 Navigate할까?

 

Navigation component를 만든다.

<a href="url"></a> 로 하는 경우, HTML! 따라서, 페이지가 매번 새로고침되고 우리가 원하는 대로 화면 전환이 이루어 지지 않는다.

따라서, react-router-dom의

Link를 사용한다!

import React from "react";
import { Link } from "react-router-dom";
import "./Navigation.css";

function Navigation(){
  return (
    <div>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
    </div>
  );
}

export default Navigation;

Navigation component의 2개 Link가 화면에 표시

화면 전환이 제대로 이루어 진다.


6.3 Sharing Props Between Routes

 

<Link>의 to는 object를 받을 수 있다.

function Navigation() {
  return (
    <div className="nav">
      <Link to="/">Home</Link>
      <Link to={{
        pathname:"/about",
        state: {
          fromNavigation: true
        }
      }}>About</Link>
    </div>
  );
}

to를 통해 pathname으로 이동하면서 state로 정보를 전달할 수 있다.

<Link to={{
  pathname: "/movie-detail",
  state: {
    year,
    title,
    summary,
    poster,
    genres
  }
}}>

전달된 정보(prop)을 console.log

📌 Link를 통해 정보를 Router로 보낸다.

6.4 Redirecting

Link를 통해 받은 정보는 Router가 이용할 수 있다.

 

Link(영화)를 누르지 않고, url에 movie-detail을 입력하여 이동하는 경우, state는 undefined가 된다.

영화로부터 넘겨받는 정보가 없기 때문이다.

 

이런 경우, 에러(cannot read ~~~)가 발생하고, componentDidMount( )는 동작하지 않게 된다.

해결 방법

render내에서 간단하게 if문

import React from "react";

class Detail extends React.Component{
  componentDidMount(){
    const { location, history } = this.props;
    if(location.state === undefined){
      history.push("/");
    }
  }
  render(){
    const { location } = this.props;
    if(location.state){
      return <span>{location.state.title}</span>;
    } else {
      return null;
    }
  }
}
export default Detail;
📌 render( )실행 후, componentDidMount( )가 실행된다!

 

728x90

'💻 Study > 웹' 카테고리의 다른 글

#1 USESTATE  (0) 2021.01.12
#0 INTRODUCTION - 리액트 Hooks  (0) 2021.01.10
#5 CONCLUSIONS  (0) 2021.01.10
#4 MAKING THE MOVIE APP  (0) 2021.01.10
#3 STATE  (0) 2021.01.10
'💻 Study/웹' 카테고리의 다른 글
  • #1 USESTATE
  • #0 INTRODUCTION - 리액트 Hooks
  • #5 CONCLUSIONS
  • #4 MAKING THE MOVIE APP
soyang.
soyang.
AI/Agent/개발 지식 Archive.
  • soyang.
    소소한 코딩일지
    soyang.
  • 전체
    오늘
    어제
  • 링크

    • Github 🐾
    • 포트폴리오 📓 (리뉴얼중)
    • LinkedIn 👩🏻‍💼
  • 공지사항

    • 소소한 코딩일지
  • 블로그 메뉴

    • 방명록
    • 분류 전체보기 (181)
      • 🚩 목표 & 회고 (9)
      • 📓 Papers (10)
      • 🧇 Algorithm (44)
        • 이론 (1)
        • LeetCode (2)
        • 프로그래머스 (30)
        • 백준 (11)
      • 💻 Study (47)
        • 🤖 AI 인공지능 (3)
        • Python 파이썬 (3)
        • Docker 도커 (4)
        • 웹 (20)
        • 안드로이드 (2)
        • JAVA 자바 (1)
        • Firebase (3)
        • Linux 리눅스 (10)
      • 🍪 Projects (2)
      • 🎒 학교 (44)
        • 대학원 도비 (2)
        • 21 동계 모각코: 슈붕팥붕 (13)
        • 21 하계 모각코: 와팬호 (13)
        • 20 동계 모각코: 와팬호 (13)
      • 활동들 (16)
        • 인프런 대학생 LEAF 2기 (9)
        • 2021 Silicon Valley Online .. (7)
  • 태그

    Artificial Intelligence
    목표
    인프런대학생Leaf
    리액트
    Gentoo
    프로그래머스
    error
    알고리즘
    Python
    programmers
    알고리즘스터디
    백준
    Linux
    공부
    노마드코더
    Ai
    Algorithm
    React
    코딩테스트
    모각코
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.3
soyang.
#6 ROUTING BONUS
상단으로

티스토리툴바