본문 바로가기

React

react-router-dom (4) 서브 라우트

서브라우트란?

라우트 내부에 또 라우트를 정의하는 것.

(라우트로 사용되고 있는 컴포넌트 내부에 라우트 컴포넌트를 또 사용하는 것)

 

 

 

앞 강의에서

App 컴포넌트에서 프로필 링크 2개가 있었음

-> 프로필 링크를 보여주는 Profiles라는 라우트 컴포넌트를 따로 만들고,

그 안에 Profile 컴포넌트를 서브 라우트로 사용하도록

 

 

 

 

1. Profiles.js 만들기

import React from "react";
import { Link, Route } from "react-router-dom";
import Profile from "./Profile";

const Profiles = () => {
  return (
    <div>
      <h3>User List</h3>
      <ul>
        <li>
          <Link to="/profile/yumcoding">yumcoding</Link>
        </li>
        <li>
          <Link to="/profile/myfav">MyFav</Link>
        </li>
      </ul>
      <Route path="/profiles" exact render={() => <div>Choose an User</div>} />
      <Route path="/profiles/:username" component={Profile} />
    </div>
  );
};

export default Profiles;

 

첫 번쨰 Route 컴포넌트에 component 대신 render라는 props를 넣어줬다.

컴포넌트 자체를 전달하는 것이 아니라

보여 주고 싶은 JSX를 넣어줄 수 있다.

(따로 컴포넌트를 또 만들기 애매한 상황이나 컴포넌트에 props를 별도로 넣어주고 싶을 때 사용)

 

그리고 exact={true}가 아니라 그냥 exact라고 넣어줬는데,

JSX에서 props를 설정할 때 값을 생략하면 자동으로 true로 설정 되기 때문.

 

 

 

2. App.js

 

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

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>
      </ul>
      <hr />
      <Route path="/" component={Home} exact={true} />
      <Route path={["/about", "/info"]} component={About} />
      <Route path="/profiles" component={Profiles} />
    </div>
  );
};
export default App;

 

 

localhost:3000/profiles

 

 

 

 

localhost:3000/profiles/yumcoding

 

 

 

 

 

 

 

 

출처: 김민준, 리액트를 다루는 기술 개정판, 2019, 339~341페이지