리액트 같은 싱글 페이지 어플리케이션(SPA)에서 페이지를 이동하지 않고
페이지에 필요한 컴포넌트를 불러와서 보여준다. 이때 필요한 것이 리액트 라우터 돔이다.
1. 설치
react-router-dom을 모듈로 사용하기 위해 npm에서 설치
npm install react-router-dom --save
설치확인
2. 기본 코드
아래 주소 코드를 참고하여 app.js 수정
단, 예전과 변경된 점이 있음
1. 'Switch' is not exported from 'react-router-dom' 에러
Switch가 Routes로 바뀜
2. route 등록방식
변경 전
<Route path="/login" compoent={<LoginPage />} />
//or
<Route path="/login">
<LoginPage />
</Route>
변경 후
<Route exact path="/" element={<LoginPage />} />
https://v5.reactrouter.com/web/example/basic
Declarative routing for React apps at any scale | React Router
Version 6 of React Router is here! React Router v6 takes the best features from v3, v5, and its sister project, Reach Router, in our smallest and most powerful package yet.
reactrouter.com
App.js
import React from 'react'
import {
BrowserRouter as Router,
Routes,//이전에 Switch가 Routes로 바뀜
Route,
Link
} from "react-router-dom";
import LandingPage from './components/views/LandingPage/LandingPage';
import LoginPage from './components/views/LoginPage/LoginPage';
import RegisterPage from './components/views/RegisterPage/RegisterPage';
function App() {
return (
<Router>
<div>
{/*
A <Switch> looks through all its children <Route>
elements and renders the first one whose path
matches the current URL. Use a <Switch> any time
you have multiple routes, but you want only one
of them to render at a time
*/}
<Routes>
<Route exact path="/" element={<LandingPage />} />
<Route path="/login" compoent={<LoginPage />} />
<Route path="/register" element={<RegisterPage />} />
</Routes>
</div>
</Router>
);
}
export default App;
*exact는 path 속성에 넣은 경로값이 정확히 URL의 경로값과 일치할 때만 렌더링되도록 돕습니다. 만일 exact를 사용하지 않으면 path="/" 인 라우터는 /login경로에서도 반응
'Frontend > react' 카테고리의 다른 글
Proxy란? (0) | 2022.07.20 |
---|---|
axios/CORS/Proxy (0) | 2022.07.19 |
react 프로젝트 boiler-plate 기본 구조 생성 (0) | 2022.07.14 |
react 설치 (0) | 2022.07.11 |
react 특징 (0) | 2022.07.11 |