1) 페이지 컴포넌트 만들기
2) Router.js 파일 생성해서 구성코드 만들기
Router.js
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from "../pages/Home";
import About from "../pages/About";
import Contact from "../pages/Contact";
import Works from "../pages/Works";
const Router = () => {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="about" element={<About />} />
<Route path="contact" element={<Contact />} />
<Route path="Works" element={<Works />} />
</Routes>
</BrowserRouter>
);
};
export default Router;
App.js
import "./App.css";
import Router from "./shared/Router";
function App() {
return <Router />;
}
export default App;
3) React Router Dom Hook
Home.jsx
import React from "react";
import { useNavigate } from "react-router-dom";
function Home() {
const navigate = useNavigate();
return (
<div>
Home
<br />
<button
onClick={() => {
navigate("/works");
}}
>
works로 이동
</button>
</div>
);
}
export default Home;
Works.jsx
import React from "react";
import { useNavigate } from "react-router-dom";
function Works() {
const navigate = useNavigate();
return (
<div>
Works
<br />
<button
onClick={() => {
navigate("/");
}}
>
Home으로 이동
</button>
</div>
);
}
export default Works;
import React from "react";
import { useLocation, useNavigate } from "react-router-dom";
function Works() {
const navigate = useNavigate();
const location = useLocation();
console.log("location : ", location);
return (
<div>
Works
<br />
<button
onClick={() => {
navigate("/");
}}
>
Home으로 이동
</button>
</div>
);
}
export default Works;
import React from "react";
import { Link } from "react-router-dom";
function Works() {
return (
<div>
Works
<br />
<button>Home으로 이동</button>
<Link to="/contact">contact 페이지로 이동하기</Link>
</div>
);
}
export default Works;
4) children 용도
어떤 컴포넌트들은 어떤 자식 엘리먼트가 들어올지 미리 예상할 수 없는 경우가 있다. 범용적인 '박스'역할을 하는 Sidebar 혹은 Dialog와 같은 컴포넌트에서 특히 자주 볼 수 있다.
Layout.js
function Layout({ children }) {
return (
<div>
<Header />
<div style={{...layoutStyles}}>
{children}
</div>
<Footer />
</div>
);
}
Router.js
import React from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Home from '../pages/Home';
import About from '../pages/About';
import Contact from '../pages/Contact';
import Works from '../pages/Works';
import Layout from './Layout';
const Router = () => {
return (
<BrowserRouter>
<Layout>
<Routes>
<Route path="/" element={<Home />} />
<Route path="about" element={<About />} />
<Route path="contact" element={<Contact />} />
<Route path="works" element={<Works />} />
</Routes>
</Layout>
</BrowserRouter>
);
};
export default Router;