React Router 사용해보기

kyeongboo·2023년 5월 13일

React Router

Router란?

페이지 이동이라는 기능을 처리할 수 있도록 해주는 것이 라우팅이고 사용자가 요청한 url에 따라 해당 url에 맞는 페이지를 보여주는 것이라고 생각할 수 있다.

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

function App() {
  return (
    <BrowserRouter>
      {/* 라우트를 감싸줍니다. */}
      <Routes>
        <Route path="/" element={<Index />}/>
        <Route path="/one" element={<One />}/>
        <Route path="/two" element={<Two />}/>
        <Route path="/three" element={<Three />}/>
      </Routes>
    </BrowserRouter>
  );
}

function Index(){
  return <h1>hello world0</h1>
}

function One(){
  return <h1>hello world1</h1>
}

function Two(){
  return <h1>hello world2</h1>
}

function Three(){
  return <h1>hello world3</h1>
}

export default App;

위 코드 내용에서 다음 코드의 의미를 살펴보자면

import { BrowserRouter, Routes, Route } from "react-router-dom";
  • BrowserRouter
    UI와 URL을 연결합니다. HTML5를 지원하는 브라우저의 주소를 감지합니다.
  • Routes
    현재 URL과 매칭된 UI를 렌더링하는 역할을 합니다.
  • Routes
    URL이 변경되면 Routes는 모든 자식 Route를 살펴보고 가장 알맞는 것을 매칭합니다.
  • Link
    클릭하면 애플리케이션 내에서 새로운 경로로 이동하는 링크를 생성하는 컴포넌트 입니다. HTML5 History API를 사용해서 브라우저의 주소를 바꿔주는 것이기 때문에 페이지를 새로 불러오지 않고 dom만 조작해서 페이지를 보여줍니다.
<Link to="/about">home</Link>

위 코드에서 to의 의미는 접근할 경로를 의미합니다. 객체의 형태로 경로를 넣어줄 수 있습니다.

다음은 Link 컴포넌트를 이용한 모습입니다.

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

function App() {
  return (
    <BrowserRouter>
      <Link to="/"> home </Link>
      <Link to="/one"> one </Link>
      <Link to="/two"> two </Link>
      <Link to="/three"> three </Link>
      {/* 라우트를 감싸줍니다. */}
      <Routes>
        <Route path="/" element={<Index />}/>
        <Route path="/one" element={<One name='licat' />}/>
        <Route path="/two" element={<Two />}/>
        <Route path="/three" element={<Three />}/>
      </Routes>
    </BrowserRouter>
  );
}

function Index(){
  return <h1>hello world0</h1>
}

function One({name}){
  return <h1>{name} world1</h1>
}

function Two(){
  return <h1>hello world2</h1>
}

function Three(){
  return <h1>hello world3</h1>
}

export default App;

파라미터 설정

/:id는 동적 라우팅을 위해 사용되는 url 패턴 입니다.

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

function App() {
  return (
    <BrowserRouter>
	  <Link to="/blog/1"> four_1 </Link>
      <Link to="/blog/2"> four_2 </Link>
      <Link to="/blog/3"> four_3 </Link>
      <Routes>
        <Route path="/blog/:id" element={<Blog />}/>
      </Routes>
    </BrowserRouter>
  );
}

function Blog(){
	const location = useLocation();
    return <h1>hello Blog</h1>
}

export default App;

아래와 같이 파라미터만 잘라내주는 훅을 사용하셔도 됩니다.

// 파라미터 사용 예1
const location = useLocation();
const path = location.pathname.split('/')[2]

// 파라미터 사용 예2
import { BrowserRouter, Routes, Route, useParams } from "react-router-dom";
const { id } = useParams()
profile
적극성과 커뮤니케이션 능력이 겸비된 개발자로 성장하자!

0개의 댓글