[React] 라우팅

Esther.·2024년 8월 17일

멋사TIL

목록 보기
9/10

라우팅

💡 웹 애플리케이션에서 사용자가 URL을 통해 페이지에 접근할 때 해당 URL에 따라 서로 다른 컴포넌트를 보여주는 것.

Untitled

react-router-dom 라이브러리 사용 : npm start react-router-dom@6

import {BrowserRouter, Routes, Route} from 'react-router-dom'

모듈특징
BrowserRouter- history API 활용해 history 객체 생성
  • history API는 내부적으로 stack자료 형태 : url 차곡차곡 쌓는 형태
  • 라우팅 진행할 컴포넌트 상위에 생성하고 감싸주어야 함 |
    | Routes | - 모든 Route의 상위 경로에 존재해야 하며, location 변경 시 하위에 있는 모든 Route를 조회해 현재 location과 맞는 Route를 찾아준다! |
    | Route | - 현재 브라우저의 location 상태에 따라 다른 element 렌더링
  • Route.element 조건 맞을 때 렌더링할 element ( 형태)
  • Route.path 현재 path값이 url과 일치하는지 확인해 해당 url에 매칭된 element 렌더링 |

index.js

import { BrowserRouter, Routes, Route, Link} from 'react-router-dom';

const Router = () => {
  return (
    <BrowserRouter>
        <Routes>
          <Route path="/" element={<GalleryPage />} />
          <Route path="/gallery" element={<DetailCardPage />}>
            <Route path=":cardId" element={<DetailCard />} />
          </Route>
        </Routes>
    </BrowserRouter>
  );
};

(URL)~/ 일 때 : GalleryPage 보여줌

(URL)~ /gallery 일 때 : DetailCardPage 보여줌

(URL)~ /{cardID} 일 때 : DetailCard 보여줌

useNavigate()

: 조건(회원가입 등)을 만족했을 때 페이지 이동을 하게 하는 함수

↔ Link : 클릭 시 페이지를 바로 이동하게 하는 기능

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

💡 `navigate(-1)` : 뒤로 한 페이지 이동 `navigate(1)` : 앞으로 한 페이지 이

: 중첩된 라우트 렌더링하기 위해 사용되는 컴포넌트

function App(){
	return(
		<BrowserRouter>
			<Routes>
				<Header/>
				<SideBar/>
				<Route path="/a-page" element = {<PageA/>}/>
				<Route path="/b-page" element = {<PageB/>}/>
				<Route path="/c-page" element = {<PageC/>}/>
			</Routes>
		</BrowserRouter>
	);
}/

이 코드의 문제점→ <Header/> , <SideBar/> 의 반복 사용

  1. 모든 페이지들에 Header와 Sidebar 컴포넌트 나오게 되어 원하는 화면으로 렌더링 X
  2. 추후 다른 페이지 라우팅할 때 복잡해질 수 있음

⇒ Outlet 컴포넌트 사용!

//App.js
function App(){
	return(
		<BrowserRouter>
			<Routes>
				<Route exact path="/" element={<Home/>}>
					<Route path="/a-page" element = {<PageA/>}/>
					<Route path="/b-page" element = {<PageB/>}/>
					<Route path="/c-page" element = {<PageC/>}/>
				</Route>
			</Routes>
		</BrowserRouter>
	);
}
//Home.js
import {Outlet} from "react-router-dom";
import styled from "styled-components"; //후에 설명

	const ContentSection = styled.section` 
		//...
	`;
	
	const Home =()=> {
		return(
			<>
				<Header />
				<Sidebar />
				<ContentSection>
					<Outlet/>
				</ContentSection>
			</>
		);
	};
	
	export default Home;
	

URL 파라미터 사용

: url 뒤에 유동적으로 붙는 파라미터 값. → 라우트 정의할 때 path 값으로 :파라미터 변수 지정

<Route path = "/a/:id" element = { A ID } />

→ /a/123 url로 접근 시 URL파라미터(id) == 123

useParams

/a/123 url로 접근 시 렌더링 되는 페이지에서 ‘123’값 얻기 위해 사용

function A(){
	const {id} = useParams();
	return (
		<div>
			{id}
		</div>
	)
}

export default A;

find()

: 배열에서 특정 조건을 만족하는 요소를 찾아 첫 번째 요소를 반환하는 함수,

콜백 함수를 사용해 원하는 조건의 요소를 찾음

함수적용할배열.find(콜백함수)

const colors = ["red", "green", "blue"];

//콜백 함수
function findGreen(color){
	return color === "green";
}

//배열에서 조건을 만족하는 첫번째 요소를 찾음 -> green
const green = colors.find(findGreen);

styled-components

css파일 대신 js파일 내에서 스타일 해결

npm install styled-components

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

	let 변수 이름 = styled.컨포넌트이름`
		background : ${props => props.bg}; //bg이라는 porps이용가능
		//-> <컨포넌트이름 bg ="blue"> 처럼 재활용가능 
		color : black;
		padding : 10px;	
	`

LifeCycle Method (생명주기 메서드)

: 컴포넌트가 브라우저상에 나타나고, 업데이트되고, 사라지게 될 때 호출

Mounting (생성)

Component 함수가 실행되고 결과물로 나온 Element들이 가상 DOM에 삽입되고 실제 DOM을 업데이트하기까지의 과정.

Update(업데이트)

: Component들은 state 나 props 가 변경이 되면 update가 진행이 되며 다시 rendering 됨.

Unmount(제거)

:해당하는 Component가 DOM상에서 제거가 될 때 실행되는 lifeCycle

useEffect

import React, {useEffect} from 'react';

useEffect(function, deps)

기본형태

useEffect(()=>{
	console.log("");
})

ComponentDidUpdate

cosnt { exampleProp } = props;
const [count, setCount] = useState(0);

useEffect(() => {
	console.log("count or exampleProp changed");     
},[count, exampleProp]);

ComponentDidMount

useEffect(()=>{
	console.log("component
},[])

ComponentWillUnmount

useEffect(()=>{
console.log("");

return(() => exampleAPI.unsubscribe());
})

0개의 댓글