React Router

jaehan·2022년 5월 14일
0

React

목록 보기
5/33
post-thumbnail

react-router-dom v6 버전을 기준으로 정리해 보겠다.

🖥 React Router

라우터 관련 라이브러리 설치

npm add react-router-dom 설치

프로젝트에 라우터 적용

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <BrowserRouter>
    <App />
  </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(); 

react-router-domBrowserRouter를 이용하면 된다

페이지 만들기

Home.js

import React from 'react';

const Home = () => {
  return (
    <div>
      <h1></h1>
      <p>이곳은 홈화면 입니다.</p>
    </div>
  );
};

export default Home;

About.js

import React from 'react';

const About = () => {
  return (
    <div>
      <h1>소개</h1>
      <p>리액트 라우터 연습</p>
    </div>
  );
};

export default About;

Route

특정 주소에 컴포넌트를 연결하는 컴포넌트
<Route path="주소규칙" component={보여주고싶은 컴포넌트}>
📌 v6 부터는 <Routes>로 묶어줘야한다

import React from 'react';
import { Route , Routes, Link} from 'react-router-dom';
import About from './About';
import Home from './Home';
import Profile from './Profile';

const App = () => {
  return (
    <div>
      <ul>
        <li>
          <Link to ='/'></Link>
        </li>
        <li>
          <Link to ='/about'>소개</Link>
        </li>
      </ul>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>

    </div>
  );
};

export default App;

📌 Link컴포넌트는 클릭하면 다른 주소로 이동시키는 컴포넌트 이다 < a > 태그는 페이지를 새로 불러들이기 때문에 Link태그를 이용해야 한다.

파라미터와 쿼리

파라미터 : /profiles/kim
쿼리 : /about?detaile=true

파라미터

📌 v6 부터는 useParams()함수 사용해야 함.

Profile.js

import React from 'react';
import {useParams} from 'react-router-dom'
const profileData = {
    jaehan: {
        name : '김재한',
        description:
        'Fontend 공부중.'
    },
    gildong:{
        name:'홍길동',
        description:
        '아버지를 아버지라 부르지 못함.'
    }
};

const Profile = () => {
    const {username} = useParams();
    const profile = profileData[username];
    if( !profile){
        return <div>존재하지 않는 데이터</div>;
    }
    return(
        <div>
            <h3>
                {username}({profile.name})
            </h3>
            <p>
                {profile.description}
            </p>
        </div>
    );
};

export default Profile;

App.js
<Route path="/profiles/:username" element = {<Profile/>}/> 추가 해준다.

:username을 파라미터로 넣어주어서 Profile컴포넌트에서 전달받을 수 있다.

profiles/jaehan 결과

profiles/gildong 결과

쿼리

loaction 객체

{
  key: 'ac3df4', // not with HashHistory!
  pathname: '/somewhere'
  search: '?some=search-string',
  hash: '#howdy',
  state: {
    \[ userDefined ]: true
  }
}

📌 쿼리는 search값에서 읽어올 수 있다.

v6 부터는 useLocation() 사용해야 한다

About.js

import React from 'react';
import { useLocation } from 'react-router-dom';

const About = () => {
  const {search} = useLocation();
  const detail = search === '?detail=true';
  
  return (
    <div>
      <h1>소개</h1>
      <p>리액트 라우터 연습</p>
      {detail && <p>추가적인정보</p>}
    </div>
  );
};

export default About;

useLocation으로 쿼리를 잘 받아온것을 확인할 수 있다.

서브라우트

서브라우트는 라우트 내부의 라우트를 만드는 것이다.

Profiles.js


import React from 'react';
import Profile from './Profile';
import {Route, Routes, Link} from 'react-router-dom'

const Profiles = () => {
    return(
        <div>
            <h3>유저 목록:</h3>
            <ul>
                <li>
                    <Link to="/profiles/jaehan">jaehan</Link>
                </li>
                <li>
                    <Link to="/profiles/gildong">gildong</Link>
                </li>
            </ul>
            <Routes>
                <Route path='/*' element={'유저를 생성해주세요'}/>
                <Route path=":username" element={<Profile/>} />
                
            </Routes>
        </div>
    );
};

export default Profiles;

📌 v6 에서는 render 대신 element에 바로 사용해도 되고 path에 '/profiles'할 필요없이 '/*'으로 설정해 주면 된다.

App.js

import React from 'react';
import { Route , Routes, Link} from 'react-router-dom';
import About from './About';
import Home from './Home';
import Profiles from './Profiles';

const App = () => {
  return (
    <div>
      <ul>
        <li>
          <Link to ='/'></Link>
        </li>
        <li>
          <Link to ='/about'>소개</Link>
        </li>
        <li>
          <Link to = '/profiles'>프로필 목록</Link>
        </li>
      </ul>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/profiles/*" element = {<Profiles/>}/>
      </Routes>

    </div>
  );
};

export default App;

📌 App.js에도 'profiles/*'로 path설정 해주면 된다.

0개의 댓글