프론트엔드 개발/React

[React] Router - JSX로 라우팅 이동하기

Jongung 2022. 7. 5. 22:47

보통 우리가 페이지 이동을 구현 할 때 <a href=블라블라>를 사용하여 만들었을 것이다.

하지만 a 태그를 사용 했을 때 문제가 있다. <a> 는 페이지가 이동 할 때 js와 css 모두 다시 다운로드 한다는 문제점이 있다.

React Application은 SPA 방식으로 한 번 다운로드 하고 나선 다운로드 하지 않기 때문에 react-router-dom을 이용하여 Link를 사용해주어야 한다. 

App.js

import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Home from './pages/Home';
import Profile from './pages/Profile';
import About from './pages/About';
import NotFound from './pages/NotFound';
import Links from './components/Links';

function App() {
  return (
    <BrowserRouter>
      <Links /> /* 링크들이 모여 있는 컴포넌트 */
      <Switch>
        <Route path="/profile/:id" component={Profile} />
        <Route path="/profile" component={Profile} />
        <Route path="/about" component={About} />
        <Route path="/" exact component={Home} />
        <Route component={NotFound} />
      </Switch>
    </BrowserRouter>
  );
}

export default App;

 

Links.jsx

import { Link } from 'react-router-dom';

export default function Links() {
  return (
    <ul>
      <li>
        <Link to="/">Home</Link>
      </li>
      <li>
        <Link to="/profile">Profile</Link>
      </li>
      <li>
        <Link to="/profile/1">Profile/1</Link>
      </li>
      <li>
        <Link to="/about">About</Link>
      </li>
      <li>
        <Link to="/about?name=mark">About?name=mark</Link>
      </li>
    </ul>
  );
}
  • 다음과 같이 작성하면 굉장히 빠르게 전환 된다.
  • 서버에서 파일을 가져오는 것이 아닌 리액트 컴포넌트의 View만 변경되기 때문이다.

레퍼런스