개발세발

SPA, React router 본문

코딩공부/React

SPA, React router

뉼👩🏻‍💻 2022. 12. 3. 15:58
728x90
반응형
SMALL

📍SPA(Single Page Application - 싱글 페이지 애플리케이션)

- 한 개의 페이지로 이루어진 애플리케이션

애플리케이션을 브라우저에 불러와서 실행시킨 후에 사용자와의 인터랙션이 발생하면 필요한 부분만 자바스크립트를 사용하여 업데이트를 해줌
➡️ 새로운 데이터가 필요하다면 서버 API를 호출하여 필요한 데이터만 새로 불러와 애플리케이션에서 사용

📍라우팅

: 다른 주소에 다른 화면을 보여주는 것
- 리액트 라이브러리 자체에는 이 기능이 내장되어 있지 않아 브라우저의 API를 직접 사용하여 이를 관리하거나, 라이브러리를 사용하여 구현

- 리액트 라우터 : 클라이언트 사이드에서 이루어지는 라우팅을 아주 간단하게 구현할 수 있도록 해줌
+ 서버 사이드 렌더링을 할 때도 라우팅을 도와주는 컴포넌트들을 제공해줌
- 서버 사이드 렌더링
: UI를 서버에서 렌더링하는 것

◼️ SPA의 단점
: 앱의 규모가 커지면 자바스크립트 파일이 너무 커질 수 있음
- 실제로 사용자가 방문하지 않을 수도 있는 페이지의 스크립트도 불러오기 때문
➡️ 코드 스플리팅 (code splitting) : 라우터별로 파일들을 나누어서 트래픽과 로딩 속도를 개선할 수 있음


* 왜 리액트에 라우터를 추가할까?
라우터로 구분하지 않는다면 앱안의 어디에 있던지 같은 url을 가지고 있어 하나의 특정 기능에 대한 링크(url)로 이동할 수 없다


react-router
- 버전 5가 모든 프로젝트에서 사용되는 버전

 

$ npm install
$ npm install react-router-dom // 브라우저에서 실행되는 리액트 앱의 리액트 라우터 버전

 


리액트 라우터를 사용한다
= 페이지에서 다른 경로를 처리하고 다른 경로에 대해 다른 컴포넌트를 로드하는 것

다른 컴포넌트를 로드한다 ? 해당 컴포넌트를 렌더링 한다
즉, 컴포넌트를 조건부로 렌더링 한다는 의미

index.js

import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";

import "./index.css";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

 

📍 Route 컴포넌트

: 사용자의 현재 경로에 따라 다르컴포넌트를 보여줌
- 어떤 규칙을 가진 경로에 어떤 컴포넌트를 보여 줄지 정의할 수 있음

<Route path="주소규칙" component={보여 줄 컴포넌트} />


App.js

import "./App.css";
import { Route } from "react-router-dom";
import Welcome from "./screens/Welcome";
import Products from "./screens/Products";
import MainHeader from "./components/MainHeader";

function App() {
  return (
    <div>
      <MainHeader />
      <main>
        <Route path="/Welcome">
          <Welcome />
        </Route>
        <Route path="/Products">
          <Products />
        </Route>
      </main>
    </div>
  );
}

export default App;

 

📍 Link 컴포넌트

: 클릭하면 다른 주소로 이동시켜 주는 컴포넌트

a태그를 사용해서도 페이지 전환이 일어날 수 있지만 그러한 경우에는 페이지 자체가 새로고침 되는 것이므로 사용자가 입력한 정보가 날아간다. 렌더링된 컴포넌트들도 모두 사라지고 다시 처음부터 렌더링하기 때문이다. 그래서 새로고침 없이 페이지 전환을 하기 위해서 react-router-dom의 Link를 사용한다

Link 컴포넌트를 사용하여 페이지 전환시 애플리케이션은 그대로 유지한 상태에서 HTML5 History API를 사용하여 페이지의 주소만 변경함

Link 컴포넌트 자체는 a태그로 이루어져 있지만, 페이지 전환을 방지하는 기능이 내장되어 있다.

<Route path="주소규칙" component={보여 줄 컴포넌트} />

 

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

const MainHeader = () => {
  return (
    <header>
      <nav>
        <ul>
          <li>
            {/* 새로고침 되므로 SPA에 위반 */}
            {/* <a href="/welcome">Welcom</a> */}
            <Link to="/welcome">welcome</Link>
          </li>
          <li>
            {/* <a href="/Products">Products</a> */}
            <Link to="/Products">products</Link>
          </li>
        </ul>
      </nav>
    </header>
  );
};




useParams

App.js

//생략
		<Route path="/products/:productId">
          <ProductDetail />
        </Route>
//생략

productDetail.js

import { useParams } from "react-router-dom";

const ProductDetail = () => {
  const params = useParams();
  console.log(params.productId);
  return (
    <section>
      <h1>Product Detail</h1>
      <p>{params.productId}</p>
    </section>
  );
};

* 일전에 프로젝트 하면서 알게 된 params를 활용하는 방법과 동일한 방법

 

📍exact

( 반드시 path="/" 앞에 안 붙여도 되고 태그 안에 있으면 된다)

product 페이지와 product Detail페이지가 동일하게 /prodcuts로 시작하여
/products 와 /products/p1 페이지 둘 다 불러오게 됨
➡️ exact라는 props를 줘서 정확하게 url 값이 같을 때만 해당 페이지 정보를 불러올 수 있도록 설정

*참고자료
https://stackoverflow.com/questions/49162311/react-difference-between-route-exact-path-and-route-path

 

React : difference between <Route exact path="/" /> and <Route path="/" />

Can someone explain the difference between <Route exact path="/" component={Home} /> and <Route path="/" component={Home} /> I don't know the meaning of exact.

stackoverflow.com


App.js

//생략
    <Route path="/Products" component={Products} exact>
          <Products />
    </Route>
    <Route path="/products/:productId">
          <ProductDetail />
    </Route>
//생략

 

📍Switch

exact 이 정확하게 url이 맞는 결과를 리턴한다면
switch는 첫번재로 path가 맞는 결과만 리턴한다
➡️ 일반적으로 알고 있는 switch 문처럼 생각!

https://stackoverflow.com/questions/45122800/react-router-switch-behavior

 

React router Switch behavior

(react-router-dom version: 4.1.1) I have working routes set up, but I'm a bit confused about why the <Switch> was necessary: index.js import React from 'react'; import { HashRouter, Route,

stackoverflow.com


App.js

import "./App.css";
import { Route, Switch } from "react-router-dom";
import Welcome from "./screens/Welcome";
import Products from "./screens/Products";
import ProductDetail from "./screens/ProductDetail";
import MainHeader from "./components/MainHeader";

function App() {
  return (
    <div>
      <MainHeader />
      <main>
        <Switch>
          <Route path="/Welcome" component={Welcome}>
            <Welcome />
          </Route>
          <Route path="/Products" component={Products} exact>
            <Products />
          </Route>
          <Route path="/products/:productId">
            <ProductDetail />
          </Route>
        </Switch>
      </main>
    </div>
  );
}

export default App;

 

 

📍Redirect

: 렌더링 되면서 to="/"에서 지정한 url로 자동 이동하게 됨

http://localhost:3000/
http://localhost:3000/welcome


App.js

 //생략
          <Route path="/" exact>
            <Redirect to="/welcome" />
          </Route>
 //생략







728x90
반응형

'코딩공부 > React' 카테고리의 다른 글

react하면서 만난 오류들  (0) 2022.12.08
React 궁금증  (0) 2022.12.07
리액트 - 3️⃣ (feat. 리액트를 다루는 기술)  (0) 2022.12.02
React - 2️⃣ (한입 크기로 잘라먹는 리액트)  (0) 2022.11.24
React - 1️⃣  (0) 2022.10.18