728x90
반응형
SMALL
📍라우팅
- 흔히 말하는 '페이지 이동'
- 정적 라우팅/동적 라우팅
- 기본 라우팅 (정적 라우팅부터)
// 가장 기본적인 라우팅 설정
import { BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
2. 동적 라우팅
- URL에서 변수처럼 변하는 부분을 처리하는 방식
- 예: /users/:id, /products/:category/:id
// 동적 라우팅 예시
<Route path="/users/:id" element={<UserProfile />} />
<Route path="/products/:category/:id" element={<ProductDetail />} />
[React] 리액트 동적 라우팅(Dynamic Routing) - useLocation, useNavigate, useParams, useSearchParams
[React] 리액트 동적 라우팅(Dynamic Routing) - useLocation, useNavigate, useParams, useSearchParams
📌 동적 라우팅(Dynamic Routing)웹 애플리케이션에서 클라이언트의 요청에 따라 경로를 동적으로 처리하는 라우팅 방식입니다.사용자의 입력, 상태 변화, 또는 다양한 조건에 따라 서버가 어떤 페
creative103.tistory.com
📍SPA( singel page application)
- 리액트는 spa방식으로 하나의 index.html 템플릿에 여러 컴포넌트들을 넣음
📍리액트 Router Dom
- 웹 앱에서 동적 라우팅 구현 가능
- 실행중인 앱 외부에서 라우팅 되는 기존의 방식과 달리
(컴포넌트 기반 라우팅) 신규 페이지를 불러오지 않는 상황에서 각각의 url에 따라 선택된 데이터를 하나의 페이지에서 렌더링 해주는 라이브러리
- 각 프로젝트마다 설치 필요
☑️설치
npm install react-router-dom
or
npm install react-router-dom --save
yarn add react-router-dom
☑️설정
- 앱 어디서나 react router를 사용 할 수 있도록 하는 것
- src -> index.js -> react-router-dom에서 BrowserRouter를 가져오고(import) 루트구성요소(app.js)를 그 안에 매핑 시킴
- <React.StrictMode> 이건 안지워도 댐
- BrowerRouter: html5 history api를 이용하여 페이지를 새로고침하지 않고도 주소 변경할 수 있도록 함
☑️App.js
import { Route, Routes } from 'react-router-dom';
- App.js가 부모일 경우 적용 시켜줘야함
Routes : 앱에서 생성될 모든 경로에 대한 컨테이너/ 상위 역할
Route :
- 단일 경로로 사용
- path : 원하는 경로 설정
- / ) 앱이 처음 로드 될 때마다 렌더링
- index : 젤 먼저 나오게 할 페이지
☑️<Link/>
- html <a/> 와 유사
( <a href = "/about"></>) 와 동일
- to 속성 이용하여 이동하게 되는 경로 지정
📍적용
☑️페이지 생성을 위한 폴더 및 파일 추가
☑️App.js를 라우팅을 위한 파일로 변경
☑️ 예시 ) Mainpage/Index.js
import React from 'react'
import requests from "../../api/request";
import Nav from "../../components/Nav";
import styled from "styled-components";
import Banner from "../../components/Banner";
import Categroy from "../../components/Category";
import Row from "../../components/Row";
const MainPage = () => {
return (
<Container>
<Nav />
<Banner />
<Categroy />
<Row title="Trending Now"
id="TN"
fetchUrl={requests.fetchTrending}
/>
<Row title="Action Movies"
id="AM"
fetchUrl={requests.fetchActionMovies}
/>
<Row
title="Comedy Movies"
id="CM"
fetchUrl={requests.fetchComedyMovies}
/>
</Container>
)
}
export default MainPage
const Container = styled.main`
position: relative;
min-height: calc(100vh - 250px);
overflow-x: hidden;
display: block;
top: 72px;
padding: 0 calc(3.5vw + 5px);
&:after {
background: url("/images/home-background.png") center center / cover
no-repeat fixed;
content: "";
position: absolute;
inset: 0px;
opacity: 1;
z-index: -1;
}
`;
☑️ 틈새 문법
const(let)/function 차이
const Layout = () => { }
- 화살표 함수 이용
- 변수 선언 이전에 사용 불가
console.log(myFunction()); // TypeError: myFunction is not a function
const myFunction = () => {
return "Hello, World!";
};
funtion App()
- 함수 호이스팅이 적용됨 ( 변수 선언 이전에 사용 가능 )
console.log(myFunction()); // "Hello, World!"
function myFunction() {
return "Hello, World!";
}
728x90
반응형
LIST
'React > 개념' 카테고리의 다른 글
URLSearchParams (0) | 2024.01.23 |
---|---|
React Router Dom 훅 (0) | 2024.01.23 |
구조 분해 할당 (0) | 2024.01.15 |
[리액트] 컴포넌트 및 기초사항 (0) | 2024.01.12 |
#6 props - row.js (0) | 2024.01.12 |