코딩앙마 next.js 참고
오늘은 next랑 친해지는 시간을 가져봤다. 아직 react도 갈길이 멀지만 next시장이 넓어져가고 있는 요즘 더 궁금해지기 시작했다.
import "../styles/globals.css";
import "semantic-ui-css/semantic.min.css";
import Footer from "../src/component/Footer";
import Top from "../src/component/Top";
function MyApp({ Component, pageProps }) {
return (
<div style={{ width: 1000, margin: "0 auto" }}>
<Top />
<Component {...pageProps} />
<Footer />
</div>
);
}
export default MyApp;
_app.js에는 기본값으로 Component와 pageProps를 받아온다. 따로 설정해주지 않으면 default로 index.js를 불러온다.
import axios from "axios";
import Head from "next/head";
import { useEffect, useState } from "react";
import { Divider, Header, Loader } from "semantic-ui-react";
import ItemList from "../src/componenet/ItemList";
export default function Home({ list }) {
return (
<div>
... code
<ItemList list={list.slice(0, 9)} />
<Header style={{ paddingTop: 40 }}>신상품</Header>
<Divider />
<ItemList list={list.slice(9)} />
</div>
);
}
export async function getStaticProps(context) {
const API_URL = process.env.apiUrl;
const res = await axios.get(API_URL);
const data = res.data;
return {
props: {
list: data,
},
};
}
index.js에는 상품리스트를 컴포넌트가 있다.
상품api는 .env파일을 만들어 따로 저장한 후 API_URL변수에 담아 axios로 호출하고 있다.
getStaticProps를 사용하고 있는데 getStaticProps는 빌드시에 딱 한번만 호출이 된다. 빌드되었을때 값들이 수정될 경우의 수가 없거나 적은경우 사용하기 적합하다. 예를 들어 회사 소개페이지가 있다.
props를 return해주고 있는데, list에 위에서 받아온 data를 담아 Home컴포넌트에서 props로 받아 사용하고있다.
const Post = ({ item, name }) => {
.. code
export default Post;
export async function getStaticPaths() {
const API_URL = process.env.apiUrl;
const res = await axios.get(API_URL);
const data = res.data;
return {
paths: data.slice(0, 9).map((item) => ({
params: {
id: item.id.toString(),
},
})),
fallback: false,
};
}
export async function getStaticProps(context) {
const id = context.params.id;
const apiUrl = `http://makeup-api.herokuapp.com/api/v1/products/${id}.json`;
const res = await axios.get(apiUrl);
const data = res.data;
return {
props: {
item: data,
name: process.env.name,
},
};
}
getStaticPaths 라는게 있는데 이게 좀 신기했다.
getStaticPaths 는 데이터에 따라 pre-rendering할 페이지의 동적 경로를 지정하는 함수이다.
예들들어 params에 원하는 페이지만 따로 넣어주면 빌드할때 그 페이지들은 pre-rendering이 된다.
주의사항은 스크롤이 많아 뿌려지는 리스트들이 많은경우는 fallback을 false로 해놔야 효율적으로 사용이 가능하다.
import { Icon } from "semantic-ui-react";
export default function Error404() {
return (
<div style={{ padding: "200px 0", textAlign: "center", fontSize: 30 }}>
<Icon name="warning circle" color="red" />
404 : 페이지를 찾을 수 없습니다.
</div>
);
}
next에서는 에러처리에대한 페이지를 따로 지정할 수 있다.
404페이지같은경우 위처럼 따로 js파일을 만들어 커스텀이 가능하며 이외 500에러 등등은 _error.js를 만들어 커스텀이 가능하다.
export async function getServerSideProps(context) {
... code
return {
props: {
item: data,
},
};
}
getServerSideProps는 서버 사이드 렌더링을 하기위한 함수이다.
언뜻보기엔 getStaticProps와 다를게 없어보인다.
하지만 컴포넌트에 props를 넘겨주는 공통점이 있지만, 빌드시에만 실행되는것이 아니라 request때마다 실행이 된다.
첫 글 축하!👏🏻🎉✨