react-router

이짜젠·2021년 6월 24일
0

react에서 routing기능을 제공해주는 패키지다. 사용방법을 정리해본다.


설치/사용

react-rotuer-dom 설치

> npm i react-router-dom

app에 장착

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter } from 'react-router-dom'

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);

path 별 컴포넌트 설정

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

const App = () => {
    return (
        <div>
            <Route path="/" component={Home} exact={true}></Route>
            <Route path="/about" component={About}></Route>
        </div>
    );
}

export default App;
import React from 'react';
import { Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';

const App = () => {
    return (
        <div>
            <ul>
                <li>
                    <Link to="/"></Link>
                </li>
                <li>
                    <Link to="/about">소개</Link>
                </li>
            </ul>
            <hr></hr>
            <Route path="/" component={Home} exact={true}></Route>
            <Route path="/about" component={About}></Route>
        </div>
    );
}

export default App;

동적라우팅

선언

Route의 패스를 /profile/:username 형태로 선언한다.

<Route path="/profile/:username" component={Profile}></Route>

사용

기본

props.match.params[동적path_이름]으로 접근 한다.

const Profile = ({ match }) => {
    const { username } = match.params;

    return (
        <div>
            <h3>
                {username}({profile.name})
            </h3>
            <p>
                {profile.description}
            </p>
        </div>
    );
};

useRouteMatch 사용

import { useRouteMatch } from 'react-router';

const Profile = () => {
  const { params: { username } } = useRouteMatch();

    return (
        <div>
            <h3>
                {username}({profile.name})
            </h3>
            <p>
                {profile.description}
            </p>
        </div>
    );
};

[].jsx 와 useParams 사용

// [username].jsx 로 파일 생성
import { useParams } from 'react-router';

const Profile = () => {
  const { username } = useParams();

    return (
        <div>
            <h3>
                {username}({profile.name})
            </h3>
            <p>
                {profile.description}
            </p>
        </div>
    );
};

쿼리스트링 사용

props.location.search[쿼리스트링_이름]으로 접근이 가능하다.
그러나 string 형태로 되어있기에 파싱을 위해 qs 라이브러리를 사용한다.

import React from 'react';
import qs from 'qs';

const About = ({ location }) => {
    const query = qs.parse(location.search, {
        ignoreQueryPrefix: true // 맨앞 ? 생략
    });

    const showDetail = query.detail === 'true'

    return (
        <div>
            <h1>소개</h1>
            <p>이 프로젝트는 리액트 라우터 기초를 실습해 보는 예제 프로젝트입니다.</p>
            {showDetail && <p>Detail 값을 true로 설정하셨군요</p>}
        </div>
    )
}

export default About;

서브 라우트

간단하게 Route안에 Route를 넣어주면 된다.

상위라우트 컴포넌트

App.js

<div>
    <ul>
        <li>
            <Link to="/profiles">프로필들</Link>
        </li>
    </ul>
    <hr></hr>
    <Route path="/profiles" component={Profiles}></Route>
</div>

하위라우트 컴포넌트

// https://github.com/ginameee/react-playground/blob/master/router-tutorial/src/Profiles.js
<div>
    <ul>
        <li>
            <Link to="/profiles/ginameee">ginameee</Link>
        </li>
        <li>
            <Link to="/profiles/gildong">gildong</Link>
        </li>
    </ul>
    <hr></hr>
    <Route
        path="/profiles"
        exact={true}
        render={() => <div>사용자를 선택해주세요</div>}
    ></Route>
    <Route
        path="/profiles/:username"
        component={Profile}
    >
    </Route>
</div>

외부에서 라우팅정보 사용하기

라우팅에 사용된 컴포넌트가 아니어도, withRouter 를 사용하면 location, match, history 등의 routing 정보에 접근이 가능하게 해준다.

// https://github.com/ginameee/react-playground/blob/master/router-tutorial/src/WithRouterSample.js
import { withRouter } from 'react-router-dom';

const WithRouterSample = ({ location, match, history }) => {
  return (
        <div>
            <h4>location</h4>
            <textarea
                value={JSON.stringify(location, null, 2)}
                rows={7}
                readOnly
            >
            </textarea>
            <textarea
                value={JSON.stringify(match, null, 2)}
                rows={7}
                readOnly
            >
            </textarea>
            <button onClick={() => history.push("/")}>
                홈으로
            </button>
        </div>
    );
}

export default withRouter(WithRouterSample);

Switch

Path에 일치하는 단 하나의 route만을 보여준다.
일치하는 정보가 없을 때의(404) 처리도 가능하다 (path를 지정하지 않을경우 기본 페이지가 된다.)

<Switch>
    <Route path="/" component={Home} exact={true}></Route>
    <Route path="/about" component={About}></Route>
    <Route path="/profiles" component={Profiles}></Route>
    <Route path="/history" component={HistorySample}></Route>
    <Route 
        render={
            ({ location }) => (
                <div>
                    <h2>이 페이지는 존재하지 않습니다.</h2>
                    <p>{location.pathname}</p>
                </div>
            )
        }></Route>
</Switch>
profile
오늘 먹은 음식도 기억이 안납니다. 그래서 모든걸 기록합니다.

0개의 댓글