티스토리 뷰

코딩/리액트

리액트 라우터

S-RAIN 2022. 2. 7. 22:16

라우팅이란 URL 주소에 따라 어떤 UI를 보여줄지 규칙을 정하는 작업을 말한다. 기본적으로 리액트는 component에 기능이 중점되어있기 때문에 라우팅을 하기 위해서는 다른 회사의 라이브러리를 추가해야 한다.

많이 사용되는 라이브러리는 react-router-dom이다.

Route 사용법

기본적인 사용법은 아래와 같다.

  1. 패키지 설치 : npm install react-router-dom
  2. 설치한 패키지를 import해서 그 안의 BrowserRouter로 라우팅 할 컴포넌트를 감싸준다. (최상위 컴포넌트를 감싸주면 된다)
  3. 라우터를 사용할 컴포넌트에서 Router를 import해서 사용하면 된다.

Router의 사용법이 5버전에서 6버전으로 넘어가면서 꽤 바꼈다. 내 경우는 5버전 강의를 보면서 6버전을 설치했더니 아래와 같은 오류 메세지가 떴었다.

<Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

 

 

Error "Error: A <Route> is only ever to be used as the child of <Routes> element"

I am trying to use routing for the first time and followed the exact instructions from Udemy: File App.js: import { Route } from "react-router-dom"; import Welcome from "./Pages/Welc...

stackoverflow.com

위 스택플로우 질문의 답변을 통해 해결할 수 있었다. 변경 내용은 SwitchRoutes로 이름이 변경되었다는 것과 exact 옵션이 사라졌다는 것 등이 있다.

6버전의 사용 예시는 아래와 같다.

import { Route, Routes } from "react-router-dom";
import Layout from "./components/layout/Layout";
import AllMeetups from "./pages/AllMeetups";
import Favorite from "./pages/Favotites";
import NewMeetup from "./pages/NewMeetup";

function App() {
  return (
    <Layout>
      <Routes>
        <Route path="/" element={<AllMeetups />} exact={true} />
        <Route path="/new-meetup" element={<NewMeetup />} />
        <Route path="/favorite" element={<Favorite />} />
      </Routes>
    </Layout>
  );
}

export default App;

Link 사용법

또한 주의해야 할 점은 a태그 대신 Link를 사용한다는 것이다. 왜냐하면 a태그는 서버에 요청을 보내는 것이기 때문이다. 리액트는 클라이언트 사이드에서 렌더링하기 때문에 굳이 서버에 페이지를 요청하는 작업을 불필요하다.

아래와 같은 방식으로 Link를 사용할 수 있다.

import { Link } from "react-router-dom";
import classes from "./MainNavigation.module.css";

function MainNavigation() {
  return (
    <header className={classes.header}>
      <div className={classes.logo}>React Meetups</div>
      <nav>
        <ul>
          <li>
            <Link to="/">All Meetups</Link>
          </li>
          <li>
            <Link to="/new-meetup">Add New Meetup</Link>
          </li>
          <li>
            <Link to="/favorite">My Favorite</Link>
          </li>
        </ul>
      </nav>
    </header>
  );
}

export default MainNavigation;
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함