본문 바로가기

천천히 배움,/Front-End

[React] react-router

react-router

서버에 요청을 보내지 않고 클라이언트의 브라우저에서 여러 페이지들을 이동할 수 있는 클라이언트 사이드 라우팅을 도와주는 비공식 라이브러리이다.

 

<BrowserRouter>, <Switch>, <Route>, <Link>

  • <BrowserRouter>는 라우팅 관련 컴포넌트들의 최상단에 위치해야하는 컴포넌트이다.
  • <Switch>는 <Route>들을 관리하며, 다수의 <Route> path 중 일치되는 첫 번째 라우트를 실행하기 때문에 path 충돌로 인한 오류를 방지해준다.
  • <Route>는 path값이 브라우저의 URL과 일치할 때 특정 컴포넌트를 렌더링 해준다.
import React from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'
import {MovieHome, TvHome, OtherDetails} from './screens'

const App = () => {
    return (
        <Router>
            <Switch>
                <Route path={'/'} exact component={MovieHome} />
                <Route path={'/tv'} exact component={TvHome} />
                <Route path={'/movie/:id'} exact component={Details} />
                <Route path={'/tv/:id'} exact component={Details} />
                <Route path={'/other'} exact component={OtherDetails} />
            </Switch>
        </Router>
    );
};

export default App;

 

  • <Link>는 react에서 <a> 대신에 사용하는 컴포넌트로 a 태그와 달리 새로고침이 일어나지 않고, SPA를 유지한 채 화면만 전환된다.
 <Link to={`/tv/${tvItem.id}`}>
   <Button>자세히 보기</Button>
 </Link>