단순 코드 기록/RE: React

Router 기초

일일일코_장민기 2024. 5. 21. 21:33
728x90

 

1. 리액트 라우터 DOM

2. 라우터 설치 및 실행

3. Link to

4. HashRouter

5. NavLink

6. useParams

 

전체코드

더보기
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import reportWebVitals from './reportWebVitals';
import { HashRouter, Routes, Route, NavLink, useParams } from 'react-router-dom';

var contents = [
  {id: 1, title: "html", description: "html is..."},
  {id: 2, title: "js", description: "js is..."},
  {id: 3, title: "react", description: "react is..."},
];

function App(){
 
  return(
    <div>
      <h1>Hello React Router DOM</h1>
      <ul>
        <li><NavLink to='/'>home</NavLink></li>
        <li><NavLink to='/topics'>topics</NavLink></li>
        <li><NavLink to='/contact'>contact</NavLink></li>
      </ul>
      <Routes>
        <Route path='/' element={<Home></Home>}/>                  
        <Route path='/topics/*' element={<Topics></Topics>}/>
        <Route path='/contact' element={<Contact></Contact>}/>
        <Route path='/*' element={'Not Found'}/>                  
      </Routes>
    </div>
  )
}

function Home(){
  return(
    <div>
      <h2>Home</h2>
      Home...
    </div>
  )
}

function Topic(){
  var params = useParams();
  console.log(params);  //topic_id 출력
  var topic_id = params.topic_id;
  var selected_topic = {title: 'sorry', description: 'not found'};
  for (let index = 0; index < contents.length; index++) {
    const element = contents[index];
    if(element.id === Number(topic_id)){
      selected_topic = element;
      break;
    }
  }
  return(
    <div>
      <h3>{selected_topic.title}</h3>
      {selected_topic.description}
    </div>
  )
}

function Topics(){
  var list = [];
  for (let index = 0; index < contents.length; index++) {
    list.push(<li><NavLink to={'/topics/'+contents[index].id}>{contents[index].title}</NavLink></li>)
  }
  return(
    <div>
      <h2>Topics</h2>
      <ul>
        {list}
      </ul>
      <Routes>
        <Route path='/:topic_id' element={<Topic></Topic>}/>    
        {/* list의 contents[index].id가 topic_id로 전달 */}              
      </Routes>
    </div>
  )
}

function Contact(){
  return(
    <div>
      <h2>Contact</h2>
      Contact...
    </div>
  )
}

ReactDOM.createRoot(document.getElementById("root")).render(<HashRouter><App></App></HashRouter>)
reportWebVitals();

 

1. 리액트 라우터 DOM
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import reportWebVitals from './reportWebVitals';

function App(){
  return(
    <div>Hello React Router DOM</div>
  )
}

ReactDOM.createRoot(document.getElementById("root")).render(<App></App>)
reportWebVitals();

============================================================================================

2. 라우터 설치 및 실행
npm install react-router-dom
import { BrowserRouter, Routes, Route } from 'react-router-dom';
ReactDOM.createRoot(document.getElementById("root")).render(<BrowserRouter><App></App></BrowserRouter>)

function App(){
  return(
    <div>
      <Routes>
        <Route path='/' element={<Home></Home>}/>                   {/* 컴포넌트 출력 */}
        <Route path='/topics' element={<Topics></Topics>}/>
        <Route path='/contact' element={<Contact></Contact>}/>
        <Route path='/*' element={'Not Found'}/>                    {/* 글씨 출력 */}
      </Routes>
    </div>
  )
}

    1. <Route path='/' element={<Home></Home>}/>  
    / 주소에 들어가면 Home 컴포넌트 출력

    2. <Route path='/*' element={'Not Found'}/>
    지정되지 않은 주소에 들어가면 Not Found라는 글씨 출력

============================================================================================

3. Link to
- 단일 페이지 애플리케이션은 코드나 ajax를 통해 비동기적으로 데이터를 가져와서 페이지를 만들어야 함
- Link 컴포넌트: 페이지가 리로드되지 않도록 자동으로 구현

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

<li><Link to='/'>home</Link></li>
- a href --> Link to

============================================================================================

4. HashRouter
- react-router-dom에서 제공하는 라우터 중 하나
- URL의 해시 부분('#' 이후)을 사용하여 경로를 관리하는 라우터
- HashRouter를 사용하면 애플리케이션의 경로가 URL의 해시 부분에 포함됨
- 서버로 요청을 보내지 않고 클라이언트 측에서 경로를 처리할 수 있음
- 주로 서버 설정을 변경할 수 없는 환경에서 사용됨
ex: 정적 파일만 제공하는 서버에서는 BrowserRouter를 사용하면 서버가 경로를 인식하지 못하고 404 오류를 반환할 수 있움
--> HashRouter는 해시('#')를 사용하기 때문에 서버로의 요청을 방지하고 클라이언트 측에서만 경로를 처리할 수 있음

import { HashRouter, Routes, Route, Link } from 'react-router-dom';
ReactDOM.createRoot(document.getElementById("root")).render(<HashRouter><App></App></HashRouter>)

============================================================================================

5. NavLink
링크에 class="active" 속성을 부여하여 사용자에게 현재 페이지를 직관적으로 알 수 있게끔 표시할 수 있음

============================================================================================

6. useParams
- 현재 URL의 경로 매개변수(route parameters)를 가져오는 데 사용
- 경로 매개변수는 URL의 일부로, 콜론(:)을 사용하여 정의됨
- 예를 들어, 경로가 /user/:id일 때, :id 부분이 경로 매개변수
import { BrowserRouter, Routes, Route, Link, useParams } from 'react-router-dom';

function Topic(){
  var params = useParams();
  console.log(params);  //topic_id 출력
  var topic_id = params.topic_id;
  var selected_topic = {title: 'sorry', description: 'not found'};
  for (let index = 0; index < contents.length; index++) {
    const element = contents[index];
    if(element.id === Number(topic_id)){
      selected_topic = element;
      break;
    }
  }
  return(
    <div>
      <h3>{selected_topic.title}</h3>
      {selected_topic.description}
    </div>
  )
}

function Topics(){
  var list = [];
  for (let index = 0; index < contents.length; index++) {
    list.push(<li><NavLink to={'/topics/'+contents[index].id}>{contents[index].title}</NavLink></li>)
  }
  return(
    <div>
      <h2>Topics</h2>
      <ul>
        {list}
      </ul>
      <Routes>
        <Route path='/:topic_id' element={<Topic></Topic>}/>    
        {/* list의 contents[index].id가 topic_id로 전달 */}              
      </Routes>
    </div>
  )
}

    1. 전역변수로 설정된 contents로부터 전달 받아서 url로 지정(to={'/topics/'+contents[index].id})
    2. 라우터의 패스로 지정하여 contents[index].id가 topic_id라는 이름으로 전달
    3. 라우터 element로 지정된 컴포넌트에 var params = useParams(); 구현
    - params가 전달 받은 내용들
    - params.topic_id = contents[index].id
    4. for문을 사용하여, 전역변수의 아이디와 params.topic_id가 같은 경우에 selected_topic에 저장
    - selected_topic의 기본값을 지정하여, 같은 값이 없는 경우에는 에러 문구 출력


============================================================================================

 

 

 

'단순 코드 기록 > RE: React' 카테고리의 다른 글

redux toolkit 기초  (0) 2024.05.23
redux 기초  (0) 2024.05.22
Context Api 기초  (0) 2024.05.22
Styled Components 기초  (0) 2024.05.22
React 기초  (0) 2024.05.20