Programming/국비학원

220804 - 리액트 - 라우터돔

지고르 2022. 8. 5. 11:49
라우터돔 (업데이트 이전 버전)

npm i react-router-dom@5.2.0

 

Switch : 첫번째 Route(보통 메인 페이지)를 렌더링

Route : path에 지정된 url에 접속해 렌더링

Link : url로 이동 (새로고침 없이)

Useparams : 파라미터 가져옴 (URL/user/1)

 

  • index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter, Link, Route, Switch } from 'react-router-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';

function Home(){
  return(
    <div>
      <h2>SS전자 소개</h2>
      <p>모든 전자 제품의 메카</p>
    </div>
  );
}

function Products(){
  return(
    <div>
      <h2>제품 소개</h2>
      <p>다양한 제품들</p>
    </div>
  );
}

function Community(){
  return(
    <div>
      <h2>공지사항</h2>
      <p>다양한 제품들의 사용법</p>
    </div>
  );
}

function App(){
  return(
    <div>
      <h1>SS전자</h1>
      <ul>
        <li><Link exact to ='/'>SS전자 소개</Link></li> 
        <li><Link to ='/products'>제품 소개</Link></li>
        <li><Link to ='/community'>공지 사항</Link></li>
      </ul>
      <Switch> 
        <Route exact path='/'><Home></Home></Route>  {/*exact 안 할 시 path가 /이기 때문에 다른 /products 등 눌러도 해당하는 걸로 인지*/}
        <Route path='/products'><Products></Products></Route>
        <Route path='/community'><Community></Community></Route>
        <Route path='/'>페이지를 찾을 수 없습니다.</Route>
      </Switch>
    </div>
  );
}

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

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

 

 

  • NavLink

Link의 스페셜 버전 (선택한 요소에 css style 추가 가능)

클릭한 링크에만 class='active' 생성됨

 

 

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter, Link, NavLink, Route, Switch } from 'react-router-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';

function Home(){
  return(
    <div>
      <h2>SS전자 소개</h2>
      <p>모든 전자 제품의 메카</p>
    </div>
  );
}

function Products(){
  return(
    <div>
      <h2>제품 소개</h2>
      <p>다양한 제품들</p>
    </div>
  );
}

function Community(){
  return(
    <div>
      <h2>공지사항</h2>
      <p>다양한 제품들의 사용법</p>
    </div>
  );
}

function App(){
  return(
    <div>
      <h1>SS전자</h1>
      <ul>
        <li><NavLink exact to ='/'>SS전자 소개</NavLink></li>  
        <li><NavLink to ='/products'>제품 소개</NavLink></li>
        <li><NavLink to ='/community'>공지 사항</NavLink></li>
      </ul>
      <Switch> 
        <Route exact path='/'><Home></Home></Route>  {/*exact 안 할 시 /products 에도 / 가 있기 때문에, 매칭이 되어서 보여짐*/}
        <Route path='/products'><Products></Products></Route>
        <Route path='/community'><Community></Community></Route>
        <Route path='/'>페이지를 찾을 수 없습니다.</Route>
      </Switch>
    </div>
  );
}

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

 

 

 

  • 중첩 라우팅 (Nested Routing)
  •  

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter, Link, NavLink, Route, Switch } from 'react-router-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';

function Home(){
  return(
    <div>
      <h2>SS전자 소개</h2>
      <p>모든 전자 제품의 메카</p>
    </div>
  );
}

function OneProduct(){

}

function Products(){
  return(
    <div>
      <h2>제품 소개</h2>
      <ul>
        <li><NavLink to='/products/1'>냉장고</NavLink></li>
        <li><NavLink to='/products/2'>에어컨</NavLink></li>
        <li><NavLink to='/products/3'>세탁기</NavLink></li>
      </ul>
      <Switch>
        <Route path='/products/1'>양문형 냉장고는 냉동고가..</Route> 
        <Route path='/products/2'>스탠드형 에어컨과 천장형 에어컨은..</Route>
        <Route path='/products/3'>최신 세탁기는..</Route>
      </Switch>
    </div>
  );
}

function Community(){
  return(
    <div>
      <h2>공지사항</h2>
      <p>다양한 제품들의 사용법</p>
    </div>
  );
}

function App(){
  return(
    <div>
      <h1>SS전자</h1>
      <ul>
        <li><NavLink exact to ='/'>SS전자 소개</NavLink></li> 
        <li><NavLink to ='/products'>제품 소개</NavLink></li>
        <li><NavLink to ='/community'>공지 사항</NavLink></li>
      </ul>
      <Switch> 
        <Route exact path='/'><Home></Home></Route> 
        <Route path='/products'><Products></Products></Route>
        <Route path='/community'><Community></Community></Route>
        <Route path='/'>페이지를 찾을 수 없습니다.</Route>
      </Switch>
    </div>
  );
}

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

 

 

  • js 사용해 동적으로 변경

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter, Link, NavLink, Route, Switch } from 'react-router-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';

function Home(){
  return(
    <div>
      <h2>SS전자 소개</h2>
      <p>모든 전자 제품의 메카</p>
    </div>
  );
}

function OneProduct(){

}

let contents=[
  {id:1, title:'냉장고', desc:'양문형 냉장고는..'},
  {id:2, title:'에어컨', desc:'천장형 에어컨은..'},
  {id:3, title:'세탁기', desc:'드럼형 세탁기는..'}
];

function Products(){
  let list=[];
  for (let i=0;i<contents.length;i++){  
    list.push(
      <li key={contents[i].id}>
        <NavLink to={'/products/'+contents[i].id}>
          {contents[i].title}
          </NavLink>
      </li>
    );
  }
  
  return(
    <div>
      <h2>제품 소개</h2>
      <ul>
        {list}
      </ul>
    </div>
  );
}

function Community(){
  return(
    <div>
      <h2>공지사항</h2>
      <p>다양한 제품들의 사용법</p>
    </div>
  );
}

function App(){
  return(
    <div>
      <h1>SS전자</h1>
      <ul>
        <li><NavLink exact to ='/'>SS전자 소개</NavLink></li> 
        <li><NavLink to ='/products'>제품 소개</NavLink></li>
        <li><NavLink to ='/community'>공지 사항</NavLink></li>
      </ul>
      <Switch> 
        <Route exact path='/'><Home></Home></Route> 
        <Route path='/products'><Products></Products></Route>
        <Route path='/community'><Community></Community></Route>
        <Route path='/'>페이지를 찾을 수 없습니다.</Route>
      </Switch>
    </div>
  );
}

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

 

  • 세부 제품 내용도 동적으로 연결

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter, Link, NavLink, Route, Switch, useParams } from 'react-router-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';

function Home(){
  return(
    <div>
      <h2>SS전자 소개</h2>
      <p>모든 전자 제품의 메카</p>
    </div>
  );
}

function OneProduct(){
  let params=useParams(); //파라미터 가져옴
  console.log(params); //[0]: {product_id: '3'} [1]: 객체
  let _id=params.product_id; //product_id값 변수에 넣음
  let selected_product={ //페이지값 오류 시 표시할 정보
    title:'제품 없음',
    desc:'제품정보 없음'
  }

  for(let i=0;contents.length;i++){
    if(contents[i].id===Number(_id)){ //세팅된 id와 선택한 id 값 같으면
      selected_product=contents[i];
      break;
    }
  }

  return (
    <div>
      <h3>{selected_product.title}</h3> 
      <p>{selected_product.desc}</p>  
    </div>
  );
}

let contents=[
  {id:1, title:'냉장고', desc:'양문형 냉장고는..'},
  {id:2, title:'에어컨', desc:'천장형 에어컨은..'},
  {id:3, title:'세탁기', desc:'드럼형 세탁기는..'}
];

function Products(){
  let list=[];
  for (let i=0;i<contents.length;i++){
    list.push(
      <li key={contents[i].id}>
        <NavLink to={'/products/'+contents[i].id}>
          {contents[i].title}
          </NavLink>
      </li>
    );
  }

  return(
    <div>
      <h2>제품 소개</h2>
      <ul>
        {list}
      </ul>
      <Route path={'/products/:product_id'}  ><OneProduct></OneProduct></Route>
    </div>
  );
}

function Community(){
  return(
    <div>
      <h2>공지사항</h2>
      <p>다양한 제품들의 사용법</p>
    </div>
  );
}

function App(){
  return(
    <div>
      <h1>SS전자</h1>
      <ul>
        <li><NavLink exact to ='/'>SS전자 소개</NavLink></li> 
        <li><NavLink to ='/products'>제품 소개</NavLink></li>
        <li><NavLink to ='/community'>공지 사항</NavLink></li>
      </ul>
      <Switch> 
        <Route exact path='/'><Home></Home></Route>
        <Route path='/products'><Products></Products></Route>
        <Route path='/community'><Community></Community></Route>
        <Route path='/'>페이지를 찾을 수 없습니다.</Route>
      </Switch>
    </div>
  );
}

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

 

 

코드 스플리팅
필요한 만큼 컴포넌트 쪼개는 기법
페이지 나누어서 컴포넌트 제작, 재컴포넌트화해 필요할 때마다 로드 
=> 성능 좋아짐, 관리 어려워짐

 

 

 

Router 최신 버전

npm install react-router-dom

 

 

https://lienkooky.tistory.com/225

 

[TIL] 01. 새로운 react-router-dom에 관하여...(feat.v6)

React Router란? React Router는 리액트로 여러 페이지 응용 프로그램을 쉽게 만들 수 있는 리액트 구성 요소, 훅 및 유틸리티의 모음입니다. React Router는 세 가지 패키지로 npm에 게시됩니다. react-router

lienkooky.tistory.com

https://velog.io/@soryeongk/ReactRouterDomV6

 

[React] react-router-dom v6 업그레이드 되면서 달라진 것들

react-router-dom이 v6으로 업그레이드 되었습니다 :) v5와 다른 점이 몇 가지 있으니 꼭 숙지하시기 바랍니다. 안그럼 아무것도 실행되지 않을지도....

velog.io

 

 

  •  

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter, Routes, Route, NavLink } from 'react-router-dom';

function Home(){
  return(
    <div>
      <h2>SS전자 소개</h2>
      <p>모든 전자 제품의 메카</p>
    </div>
  );
}

function Products(){
  return(
    <div>
      <h2>제품 소개</h2>
      <p>인공지능을 탑재한 전자 제품들</p>
    </div>
  );
}

function Community(){
  return(
    <div>
      <h2>공지사항</h2>
      <p>다양한 제품들의 사용법</p>
    </div>
  );
}

function App(){
  return(
    <div>
      <h1>SS전자</h1>
      <ul>
        <li><NavLink to ='/'>SS전자 소개</NavLink></li>  {/* exact 필요없음 */}
        <li><NavLink to ='/products'>제품 소개</NavLink></li>
        <li><NavLink to ='/community'>공지 사항</NavLink></li>
      </ul>
      <Routes>
        <Route path='/' element={<Home></Home>}></Route>
        <Route path='/products' element={<Products></Products>}></Route>
        <Route path='/community' element={<Community></Community>}></Route>
      </Routes>
    </div>
  );
}

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

 

 

  • 상대참조

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

function Home(){
  return(
    <div>
      <h2>SS전자 소개</h2>
      <p>모든 전자 제품의 메카</p>
    </div>
  );
}

function OneProduct(){
  let params=useParams(); //세부페이지 값 가져옴
  console.log(params); //[0]: {product_id: '3'} [1]: 객체
  let _id=params.product_id; //product_id값 변수에 넣음
  let selected_product={ //페이지값 오류 시 표시할 정보
    title:'제품 없음',
    desc:'제품정보 없음'
  }

  for(let i=0;contents.length;i++){
    if(contents[i].id===Number(_id)){ //세팅된 id와 선택한 id 값 같으면
      selected_product=contents[i];
      break;
    }
  }

  return (
    <div>
      <h3>{selected_product.title}</h3>
      <p>{selected_product.desc}</p>
    </div>
  );
}

let contents=[
  {id:1, title:'냉장고', desc:'양문형 냉장고는..'},
  {id:2, title:'에어컨', desc:'천장형 에어컨은..'},
  {id:3, title:'세탁기', desc:'드럼형 세탁기는..'}
];

function Products(){
  let list=[];
  for (let i=0;i<contents.length;i++){
    list.push(
      <li key={contents[i].id}>
        <NavLink to={'/products/'+contents[i].id}>
          {contents[i].title}
          </NavLink>
      </li>
    );
  }

  return(
    <div>
      <h2>제품 소개</h2>
      <ul>
        {list}
      </ul>
      <Routes>
        <Route path={':product_id'} element={<OneProduct></OneProduct>}></Route>  
      </Routes>  //=> 불명확해서 에러 발생
    </div>
  );
}

function Community(){
  return(
    <div>
      <h2>공지사항</h2>
      <p>다양한 제품들의 사용법</p>
    </div>
  );
}

function App(){
  return(
    <div>
      <h1>SS전자</h1>
      <ul>
        <li><NavLink to ='/'>SS전자 소개</NavLink></li>  {/* exact 필요없음 */}
        <li><NavLink to ='/products'>제품 소개</NavLink></li>
        <li><NavLink to ='/community'>공지 사항</NavLink></li>
      </ul>
      <Routes>
        <Route path='/' element={<Home></Home>}></Route>
        <Route path='/products/*' element={<Products></Products>}></Route> //에러 대응
        <Route path='/community' element={<Community></Community>}></Route>
      </Routes>
    </div>
  );
}

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

 

 

  • 새로운 중첩라우터

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

function Home(){

  return(
    <div>
      <h2>SS전자 소개</h2>
      <ul>
        <li><NavLink to='/1'>CEO 인사말</NavLink></li>
        <li><NavLink to='/2'>SS전자 연혁</NavLink></li>
        <li><NavLink to='/3'>찾아오시는 길</NavLink></li>
      </ul>    
      <Routes>
        <Route path='/1' element={'aa'}></Route>
        <Route path='/2' element={'bb'}></Route>
        <Route path='/3' element={'cc'}></Route>
      </Routes>
    </div>
  );
}

function OneProduct(){
  let params=useParams(); //세부페이지 값 가져옴
  console.log(params); //[0]: {product_id: '3'} [1]: 객체
  let _id=params.product_id; //product_id값 변수에 넣음
  let selected_product={ //페이지값 오류 시 표시할 정보
    title:'제품 없음',
    desc:'제품정보 없음'
  }

  for(let i=0;contents.length;i++){
    if(contents[i].id===Number(_id)){ //세팅된 id와 선택한 id 값 같으면
      selected_product=contents[i];
      break;
    }
  }

  return (
    <div>
      <h3>{selected_product.title}</h3>
      <p>{selected_product.desc}</p>
    </div>
  );
}

let contents=[
  {id:1, title:'냉장고', desc:'양문형 냉장고는..'},
  {id:2, title:'에어컨', desc:'천장형 에어컨은..'},
  {id:3, title:'세탁기', desc:'드럼형 세탁기는..'}
];

function Products(){
  let list=[];
  for (let i=0;i<contents.length;i++){
    list.push(
      <li key={contents[i].id}>
        <NavLink to={'/products/'+contents[i].id}>
          {contents[i].title}
          </NavLink>
      </li>
    );
  }

  return(
    <div>
      <h2>제품 소개</h2>
      <ul>
        {list}
      </ul>
      <Routes>
        <Route path={':product_id'} element={<OneProduct></OneProduct>}></Route>  
      </Routes>
    </div>
  );
}

function Community(){
  return(
    <div>
      <h2>공지사항</h2>
      <p>다양한 제품들의 사용법</p>
    </div>
  );
}

function App(){
  return(
    <div>
      <h1>SS전자</h1>
      <ul>
        <li><NavLink to ='/'>SS전자 소개</NavLink></li>  {/* exact 필요없음 */}
        <li><NavLink to ='/products'>제품 소개</NavLink></li>
        <li><NavLink to ='/community'>공지 사항</NavLink></li>
      </ul>
      <Routes>
        <Route path='/*' element={<Home></Home>}></Route> 
        <Route path='/products/*' element={<Products></Products>}></Route>
        <Route path='/community' element={<Community></Community>}></Route>
      </Routes>
    </div>
  );
}

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

 

 

  • 중첩 라우터2

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

var hcontents=[
  {id:1, title:'CED인사말', desc:'저희 전자는 최첨단 시설..'},
  {id:2, title:'SS전자연혁', desc:'1990년에 설립된 저의 회사는..'},
  {id:3, title:'찾아오시는 길', desc:'종로구 관철동에서 ...'}
];

function Home() {
  var hparams=useParams();
  console.log(hparams);
  var home_id=hparams.home_id;
  var selected_home={
    title:'제품없음',
    desc:'제품정보 없음'
  };
  for(var i=0; i<hcontents.length; i++){
    if(hcontents[i].id === Number(home_id)) {
      selected_home=hcontents[i];
      break;
    }
  }
  return (
    <div>
      <h3>{selected_home.title}</h3>
      <p>{selected_home.desc}</p>
    </div>
  );
}

function Homes() {
  var list=[];
  for(var i=0; i<hcontents.length; i++){
    list.push(
      <li key={hcontents[i].id}>
        <NavLink to={'/'+hcontents[i].id}>{hcontents[i].title}</NavLink></li>
    );
  }
  return (
    <div>
      <h2>회사소개</h2>
      <ul>
        {list}
      </ul>
      <Routes>     
        <Route path=':home_id' element={<Home></Home>}/>
      </Routes>       
    </div>
  );
}
function Product() {
  var params=useParams();
  console.log(params);
  var product_id=params.product_id;
  var selected_product={
    title:'제품없음',
    desc:'제품정보 없음'
  };
  for(var i=0; i<contents.length; i++){
    if(contents[i].id === Number(product_id)) {
      selected_product=contents[i];
      break;
    }
  }
  return (
    <div>
      <h3>{selected_product.title}</h3>
      <p>{selected_product.desc}</p>
    </div>
  );
}
var contents=[
  {id:1, title:'냉장고', desc:'양문형으로 냉동고가...'},
  {id:2, title:'에어컨', desc:'스탠다드형과 벽걸이형이 있으며..'},
  {id:3, title:'세탁기', desc:'드럼과 통돌이가 있으며...'}
];

function Products () {
  var list=[];
  for(var i=0; i<contents.length; i++){
    list.push(
      <li key={contents[i].id}>
        <NavLink to={'/products/' + contents[i].id}>{contents[i].title}</NavLink></li>
    );
  }
  return (
    <div>
      <h2>제품소개</h2>
      <ul>
        {list}
      </ul>
      <Routes>      
        <Route path=':product_id' element={<Product></Product>}/>
      </Routes>        
    </div>
  );
}

function Community() {
  return (
    <div>
      <h2>커뮤니티</h2>
      <p>다양한 제품들의 올바른 사용법</p>
    </div>
  );
}

function App() {
  return (
    <div>
      <h1>SS전자</h1>
      <ul>
        <li><NavLink to='/'>SS전자소개</NavLink></li>
        <li><NavLink to='/products'>제품소개</NavLink></li>
        <li><NavLink to='/community'>커뮤니티</NavLink></li>
      </ul>
      <Routes>
        <Route path='/*' element={<Homes></Homes>}/>
        <Route path='/products/*' element={<Products></Products>}/>
        <Route path='/community' element={<Community></Community>}/>
      </Routes>
    </div>
  );
}  

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