이번 React 사이드프로젝트에 적용시켜본 Next.js를 하며 느꼈던 차이는 우선 라우팅하는 방식이었다.
Next.js는 pages폴더 내부의 폴더or파일명이 자동으로 path가 설정되기 때문에 처음엔 당황하였지만 전에 React프로젝트에서 Routes, Route, path, element를 일일히 다 적어야 했던거와 비교해보면 아주 간단하고 편했다.
React
// app.js
import { Routes , Route } from 'react-router-dom';
const App = () => {
return (
<div>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/signup" element={<Signup />} />
<Route path="/login" element={<Login />} />
<Route path="/logout" element={<Logout />} />
<Route path="/questions" element={<AllQuestions />} />
</Routes>
</div>
)
}
--------------------------------------------------------------
// index.js
import {BrowserRouter} from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
React는 react-router-dom
을 사용해 path를 설정하고 동적 라우팅의 경우 :(콜론)
을 사용하여 값을 설정해줘야 한다.
Next.js
//Next js pages 폴더 디렉토리 구조
src/pages
├── _app.tsx
├── index.tsx
├── signup ── index.tsx
├── auth
│ ├── login ── index.tsx
│ └── index.tsx
Next.js의 경우 따로 path를 설정하는 것이 아니라 /pages 혹은 /src/pages 폴더 내의 폴더명, 파일명에 맞춰 자동으로 path가 설정 된다.
(src에 pages가 있는경우 따로 만든 pages 폴더의 라우팅은 무시된다.)
동적 라우팅의 경우에는 파일명이나 폴더명을 [](대괄호)
로 감싸주면 된다.
react-router 처럼 Next.js도 next/link의 Link를 import해와서 페이지를 이동할 수 있다.
import Link from 'next/link'
function Headers() {
return (
<div>
<div>
<Link href="/">
<Main />
</Link>
</div>
<div>
<Link href="/login">
<Login />
</Link>
</div>
<div>
<Link href="/signup">
<SignUp/>
</Link>
</div>
</div>
)
}
export default Headers;
Link는 href 속성값으로 URL 객체도 받을 수 있다.
-> ex. /search?name=aaa
router.push(url, as, options)
url(필수) : 이동할 경로
as : 브라우저에서 표시된 경로
options
scroll : 기본값은 true로 페이지 이동 후 상단으로 스크롤한다.
shallow : 기본값은 false로 getStaticProps, getServerSideProps, getInitialProps 를 실행하지 않고 현재 페이지의 경로를 업데이트한다.
locale : 새 페이지의 로케일을 나타낸다.
import {useRouter} from 'next/router';
const SignUp = () => {
const router = useRouter();
return (
<div>
<div>
<button onClick={() => { router.push('/login', '/login') }}>회원가입완료</button>
</div>
</div>
)
}
export default SignUp;