본문 바로가기

React

react-router-dom (7) 부가기능 Switch

 Switch

- 컴포넌트

- 여러 Route를 감싸서 그중 일치하는 단 하나의 라우트만 렌더링 시켜준다.

- 모든 규칙과 일치하지 않을 때 보여 줄 Not Found 페이지도 구현 가능!!!!!

 

 

App.js

import React from "react";
import { Route, Link, Switch } from "react-router-dom";
import Home from "./component/Home";
import About from "./component/About";
import Profiles from "./component/Profiles";
import HistorySample from "./component/HistroySample";

import "./App.css";

const App = () => {
  return (
    <div>
      <ul>
        <li>
          <Link to="/">HOME</Link>
        </li>
        <li>
          <Link to="/about">ABOUT</Link>
        </li>
        <li>
          <Link to="/profiles">PROFILE</Link>
        </li>
        <li>
          <Link to="/history">History Sample</Link>
        </li>
      </ul>
      <hr />
      <Switch>
      <Route path="/" component={Home} exact={true} />
      <Route path={["/about", "/info"]} component={About} />
      <Route path="/profiles" component={Profiles} />
      <Route path="/history" component={HistorySample} />
      //path를 따로 정의하지 않으면 모든 상황에 렌더링
      <Route render={({location})=>(
        <div>
          <h2>Page Not Found</h2>
          <p>{location.pathname}</p>
        </div>
      )}
      />
      </Switch>
    </div>
  );
};
export default App;

 

 

 

 

 

존재하지 않는 페이지!

 

 

출처

김민준, 리액트를 다루는 기술 개정판, 2019년, 349-351페이지