/ STUDY

React로 웹 앱 만들기 - Router

Router?

앞서 React가 가지는 장점은 페이지를 실행하는데 있어서 필요한 Component들만 불러와서 보여준다는 점에서 찾을 수 있다. 여기서 Router는 어떤 Component를 불러와야하는지 일종의 이정표 기능을 담당하는 친구이다. 다시 말해 페이지의 URL에 따라 어떤 Component를 실행시킬지 알려주는 기능을 하고 있다고 생각하면 된다. indedx.js -> App.js -> Router.js -> Component Render의 구조로 프로그램이 진행되면서 Route.js에서 URL과 Component를 연결해주면 된다. 그림으로 보면 아래 그림처럼 생각하면 된다.

4-2-1

여기서 URL을 구분함에 있어서 exact={true}가 없다면 입력받은 URL에 동일하지 않고 포함 되기만 하더라도 실행하기 때문에 주의해야 한다.

function App() {
  return (
    <HashRouter>
      <Navigation />
      <Route path="/" exact={true} component={Home} />
      <Route path="/about" component={About} />
      <Route path="/movie-detail" component={Detail} />
    </HashRouter>
  );
}

사용하는 방법

npm install react-router-dom

우선 터미널에서 설치를 진행해야한다.

폴더 정리

components 그리고 routes라는 폴더를 생성해준다.

  • routes : 큰 페이지 카테고리에 해당되는 요소들을 넣어두는 폴더
"내 프로젝트의 Route.js";
const AppRouter = ({ modeObj, refreshUser, isLoggedIn, userObj }) => {
  return (
    <Router>
      <Switch>
        {isLoggedIn ? (
          <>
            <Route exact path="/">
              <Home userObj={userObj} refreshUser={refreshUser} />
            </Route>
            <Redirect from="*" to="/" />
          </>
        ) : (
          <Route exact path="/">
            <Auth />
          </Route>
        )}
      </Switch>
    </Router>
  );
};
  • components : 하나의 페이지에서 실행될 조그마한 요소들을 넣어두는 폴더

위의 코드에서 Home 또는 Auth 같이 실행할 Component를 components 폴더에 정리해두었다.

파일 간 연결해주기

상위 파일에 해당 코드를 입력해 파일들을 연결해주면 기본 세팅은 완료!

  • index.js -> App.js
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);
  • App.js -> router.js
function App() {
  return (
    <>
      <div>{init ? <AppRouter /> : "Initalizing..."}</div>
    </>
  );
}

export default App;