router설정하기 1. index.js에 <BrowserRouter>로 감싸기
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
if (typeof window !== 'undefined') {
const rootNode = document.getElementById('root');
if (rootNode) {
ReactDOM.createRoot(rootNode).render(
<BrowserRouter>
<React.StrictMode>
<App />
</React.StrictMode>
</BrowserRouter>,
);
}
}
처음에 이걸 안감싸서 Link를 쓰는 모든곳에 BrowerRouter와 라우터를 설정해줘야했다;;
router설정하기 2. Routes/index.tsx 파일 만들기
import React from 'react';
import { Route, Routes } from 'react-router-dom';
import Calendar from '../pages/Calendar';
import Property from '../pages/Property';
import AddAccount from '../pages/AddAccount';
import AddProperty from '../pages/AddProperty';
import Setting from '../pages/Setting';
export default function Router() {
return (
<div className="ac__contents">
<Routes>
<Route path="/" element={<Calendar />} />
<Route path="/property" element={<Property />} />
<Route path="/addAccount" element={<AddAccount />} />
<Route path="/addProperty" element={<AddProperty />} />
<Route path="/setting" element={<Setting />} />
</Routes>
</div>
);
}
index.js에 BrowserRouter로 감쌌기 때문에 이안에서 또 감쌀 필요는 없다.
<Routes></Routes>로 감싼 다음 안에 각각 Route의 path와 그걸 연결시킬 컴포넌트를 연결해준다.
router설정하기 3. App.tsx 에 Routes/index.tsx 불러오기
import React from 'react';
import Header from './components/Header';
import Routes from './routes';
import Dockbar from './components/Dockbar';
function App() {
return (
<div className="ac__layout">
<Header />
<Routes />
<Dockbar />
</div>
);
}
export default App;
router설정하기 4. 필요한 곳에서 <Link to="/">를 사용하여 SPA방식으로 이동하기
import React from 'react';
import { FontAwesomeIcon as Icon } from '@fortawesome/react-fontawesome';
import { solid } from '@fortawesome/fontawesome-svg-core/import.macro';
import { Link } from 'react-router-dom';
interface Props {
currentPath: string;
}
function Dockbar(props: Props) {
const { currentPath } = props;
const dockbarMenus = [
{
id: '000',
title: '홈',
path: '/',
icon: solid('calendar-day'),
},
{
id: '001',
title: '자산',
path: '/property',
icon: solid('wallet'),
},
{
id: '002',
title: '설정',
path: '/setting',
icon: solid('gear'),
},
];
return (
<nav className="dockbar">
<div className="dockbar__inner">
{dockbarMenus.map((menu) => {
return (
<Link
to={menu.path}
className={
currentPath === menu.path
? 'dockbar__menu active'
: 'dockbar__menu'
}
key={menu.id}>
<Icon icon={menu.icon} />
<span className="blind">{menu.title}</span>
</Link>
);
})}
</div>
</nav>
);
}
export default Dockbar;
반응형
'React' 카테고리의 다른 글
[React & 가계부프로젝트] JSX if else 문 만들기 (리액트로 v-if / v-else 만들어보기) (0) | 2022.06.27 |
---|---|
[React & 가계부프로젝트] onClick 함수에 파라미터 같이 넘기기 (e도 같이 넘기기) (0) | 2022.06.27 |
[React & 가계부프로젝트] useNavigate() may be used only in the context of a <Router> component. (0) | 2022.06.27 |
[React & 가계부프로젝트] useEffect 콘솔에 자꾸 2번씩 찍힐때 (0) | 2022.06.27 |
[React & 환경세팅] [eslint] document is not defined / window is not defined (0) | 2022.06.27 |