Next란
리액트 라이브러리에 프레임워크이다.
pre-reloading을 통해 미리 데이터가 렌더링 된 페이지를 가져올 수 있게 해준다.
검색엔진에 잘 노출 될 수 있도록 해주고, SSR과 CSR도 혼합해 사용 가능하다.
_app.tsx 파일
function MyApp({ Component, pageProps }) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
);
}
//props로 받은 Component는 요청한 페이지이다.
// GET / 요청을 보냈다면, Component에는 /pages/index.js파일이 props로 내려온다
// pageProps는 페이지 getInitialProps를 통해 내려 받은 props들을 의미한다.
_app.tsx에서 초기 컴포넌트를 넣고 싶다면 기존 /경로 일 대 적용되는 index.tsx를 사용하면 된다. 하지만, index.tsx를 사용하는 방법은 Component는 Props로 내려주는거다. 따라서, <Component{...pageProps}/>로 전달을 받는 방식이다.
이때, pageProps는 페이지 getInitialProps를 통해 내려받은 props를 의미한다.
props로 Component와 pageProps를 받는다.
"http://localhost:3000/"은 index.tsx를 가리키고 "http://localhost:3000/about"는 about컴포넌트를 가리킨다.
pageProps란
getInitialProps, getStaticProps, getServerSideProps를 통해 가져온 초기 속성값을 의미
만약 위의 값들이 없다면 빈 객체를 반환한다.
// about.tsx
...
export async function getStaticProps() {
const test = "Hello";
return {
props: {
test,
},
};
}
// _app.tsx
import App from 'next/app'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
MyApp.getInitialProps = async (appContext) => {
const appProps = await App.getInitialProps(appContext);
return { ...appProps }
}
export default MyApp
->만약 _app.tsx에서 pageProps르 콘솔로 찍으면 {test:'Hello'}가 출력 된다.
import App from 'next/app'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
MyApp.getInitialProps = async (appContext) => {
const appProps = await App.getInitialProps(appContext);
return { ...appProps }
}
export default MyApp
_document.tsx
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
render() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
//_app.js가 실행되면서 갖추어진 content들은 Main Component아래에 생성된다.
// 브라우저는 Main을 제외한 다른 component들을 initialize하지 않는다.
// 공통된 로직이 필요하면 _app.js를 활용한다.
Next 13버전
//
// app/layout.tsx
// 이 파일에서 적용하고자 하는 layout (헤더나 푸터 등)을 return 안에 html태그 내 넣어주면
// 적용 된다.
//
// import './globals.css' -- 삭제
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
{/*
<head /> will contain the components returned by the nearest parent
head.tsx. Find out more at https://beta.nextjs.org/docs/api-reference/file-conventions/head
*/}
<head />
<body>{children}</body>
</html>
);
}
//
// app/page.tsx
//
export default function Home() {
return <p>이것은 메인 페이지 입니다.</p>;
}
//
// app/event/page.tsx
//
export default function Event() {
return <p> 이것은 이벤트 페이지 입니다. </p>;
}
//
// app/event/[id]/page.tsx
//
export default function EventId() {
return <p> 이것은 이벤트 아이디 페이지 입니다. </p>;
}