作業ディレクトリ作成
作業ディレクトリを作成し、その中にNext JS をインストールする。
mkdir example
cd &_
&_ = 直前に指定したディレクトリ
NextJSをインストール
yarn create next-app .
TailwindCSSをインストール
yarn add -D tailwindcss postcss autoprefixer
yarn tailwindcss init -p
tailwind.config.js の内容を下記の内容に入れ替え。
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
styles/globals.css の内容を下記の内容に置き換え。
@tailwind base;
@tailwind components;
@tailwind utilities;
html,
body {
padding: 0;
margin: 0;
}
pages/index.js の内容を下記の内容に入れ替え。
import Head from 'next/head'
import Image from 'next/image'
export default function Home() {
return (
<div>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<h1 className='text-3xl text-red-500'>Hello World</h1>
</main>
</div>
)
}
styles/Home.module.css を削除。
rm -rf styles/Home.module.css
TailwindCSSが適用されているか確認。
yarn dev
http://localhost:3000 にアクセスし、下記のようになっていれば完了。
Tailwind CSSのプラグインを使用する。
ここでは「daisyui」を使用する。
yarn add daisyui
tailwind.config.js のpluginsとその下に下記を追加。
plugins: [
require('daisyui'),
],
daisyui: {
styled: true,
themes: [
{
'mytheme': {
'primary': '#570df8',
'primary-focus': '#4506cb',
'primary-content': '#ffffff',
'secondary': '#f000b8',
'secondary-focus': '#bd0091',
'secondary-content': '#ffffff',
'accent': '#37cdbe',
'accent-focus': '#2aa79b',
'accent-content': '#ffffff',
'neutral': '#3d4451',
'neutral-focus': '#2a2e37',
'neutral-content': '#ffffff',
'base-100': '#ffffff',
'base-200': '#f9fafb',
'base-300': '#d1d5db',
'base-content': '#1f2937',
'info': '#2094f3',
'success': '#009485',
'warning': '#ff9900',
'error': '#ff5724',
},
},
],
},
daisyuiの中で指定している内容
styled: true = daisyuiのスタイルを適応する。 themes: [] = テーマの色を変更する。
layoutに使用するMENUボタンをdaisyuiで作成する例
// components/navbar.js
import React from 'react'
import Link from 'next/link';
import { HiMenuAlt4 } from "react-icons/hi";
function Navbar() {
return (
<div id='navbar'>
<div className='fixed bottom-3 right-3 z-50'>
<label htmlFor="my-modal-2" className="btn bg-white border-0 bg-opacity-70 hover:bg-gray-200 modal-button text-xs text-gray-800 "><div className='text-center'><HiMenuAlt4 className='text-3xl' />MENU</div></label>
</div>
<input type="checkbox" id="my-modal-2" className="modal-toggle" />
<div className="modal">
<div className="modal-box">
{/* Menu content */}
<div>
<Link href="#"><a className="btn btn-accent">お問合せ</a></Link>
</div>
{/* Button */}
<div className="modal-action">
<label htmlFor="my-modal-2" className="btn">閉じる</label>
</div>
</div>
</div>
</div>
);
}
export default Navbar
Google Fonts をインストール
Google Fontsから使用したいフォントを選択する。 ここでは「Noto Sans JP」と「Noto Serif JP」を使用。
app.js へ<Head/>を使用してフォントのURLを入力。
<Head>
<link
href='https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@100;300;400;500;700;900&family=Noto+Serif+JP:wght@200;300;400;500;600;700;900&display=swap'
rel='stylesheet'
/>
</Head>
href = 使用したいフォントのURL
tailwind.config.js の内容を下記の内容に置き換える。
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
fontFamily: {
noto: ["Noto Sans JP"],
notoSerif: ["Noto Serif JP"],
},
},
},
plugins: [],
}
noto、notoSerif = 好きな名前。 font-noto、font-notoSerif のように設定できるようになる。
styles/golobals.css の内容を下記の内容に置き換え。
@tailwind base;
@tailwind components;
@tailwind utilities;
html,
body {
padding: 0;
margin: 0;
}
body {
@apply font-noto;
}
(ここでは、font-notoSerifは部分的に使用したいのでbodyには設定しない。)
next.config.js の内容を下記の内容に置き換え。
module.exports = {
reactStrictMode: true,
experimental: {
optimizeFonts: true,
},
}
これでフォントの設定は完了。
React iconのインストール
yarn add react-icons
使用したいアイコンをココから選択。
主にFontAwesomeを使用するのでアイコンを使用する場所で下記をインポート。
import { XXXXXX } from "react-icons/fa";
XXXXX = アイコンの名前。 XX = アイコンの頭文字2文字。
例)
「BiMenuAltRight」を使用したい場合。
import { BiMenuAltRight } from "react-icons/bi";
// アイコンを使用する
< BiMenuAltRight />
AOS JS のインストール
yarn add aos@next
_app.js に下記を入力する。
import AOS from 'aos';
import 'aos/dist/aos.css';
AOS.init()は、SSR関連の理由からuseEffectにラップする形で記述します。_app.jsに以下を追加してください。 引用元:AOSを使ったアニメーションでNext.jsページをいい感じにする
React.useEffect(() => {
AOS.init();
},[]);
_app.js全体の内容はこんな状態。
import '../styles/globals.css';
import Head from 'next/head';
import AOS from 'aos';
import 'aos/dist/aos.css';
function MyApp({ Component, pageProps }) {
React.useEffect(() => {
AOS.init();
},[]);
return (
<>
<Head>
<link
href='https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@100;300;400;500;700;900&family=Noto+Serif+JP:wght@200;300;400;500;600;700;900&display=swap'
rel='stylesheet'
/>
</Head>
<Component {...pageProps} />
</>
);
}
export default MyApp
index.js の<h1>タグに下記を追加してフェードインされたら完了。
data-aos="fade-in"
index.js 全体の内容はこんな状態。
import Head from 'next/head'
export default function Home() {
return (
<div>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<h1 data-aos="fade-in" className='text-3xl text-red-500'>Hello World</h1>
</main>
</div>
)
}
Rellax JS のインストール
yarn add react-rellax
使用方法
import Parallax from 'react-rellax'
<Parallax>
パララックスで表示したい内容。
</Parallax>
オプションを使用する場合は下記のように指定する。
<Parallax speed={6}>
パララックスで表示したい内容。
</Parallax>
オプション一覧
- as (str) : ラッパーとして使用するタグ。デフォルト:div
- centered (bool) : ビューポート上のコンポーネントを中央に配置します。
- horizontal (bool) : 水平方向スクロール
- onMove (func) : オブジェクト {x: int, y: int} を受け取るコールバック関数。
- percentage (num) : 初期スクロール率。
- speed (int) : 整数 >= -10 && <=10 でスクロール速度を決定する。デフォルト:-2
- zIndex (int) : Z軸上のオーダースコントラストコンポーネント。
- wrapper (str) : 視差位置を計算するためのラッパーとして使用するセレクタです。
microCMS の設定
READEME.md の内容を全て削除し、アカウント情報をメモする。
まずはmicroCMSのアカウントを登録するためにGoogleアカウントを作成。
その後 microCMSのアカウントを作成し、各アカウント情報をメモ。
## Google
|ID|PASS|
|---|---|
|example@gmail.com|password|
## microCMS
|ID|PASS|
|---|---|
|example|password|
microCMSには1〜3つほど記事を投稿しておきます。
microCMS API設定
詳細:microCMS + Next.jsでJamstackブログを作ってみよう
.env ファイルを作成し、API KEYを入力します。
API_KEY=XXXXX
microcms-js-sdk のインストール。
yarn add microcms-js-sdk
libs/client.js を作成してSDKの初期化をします。
mkdir libs
cd $_
touch client.js
import { createClient } from 'microcms-js-sdk';
export const client = createClient({
serviceDomain: 'XXXXX',
apiKey: process.env.API_KEY,
});
XXXXX = microCMS のURLの「*****.microcms.io」の部分
記事一覧を表示したいページを作成し、そこに記事一覧を表示する。 (ここでは pages/postlist.js を記事一覧にする。)
cd pages
touch postlist.js
内容を下記の内容にする。
import Link from "next/link";
import { client } from "../libs/client";
export default function Home({ _____ }) {
return (
<div>
<ul>
{blog.map((XXXXX) => (
<li key={XXXXX.id}>
<Link href={`/〇〇〇〇〇/${XXXXX.id}`}>
<a>{XXXXX.title}</a>
</Link>
</li>
))}
</ul>
</div>
);
}
// データをテンプレートに受け渡す部分の処理を記述します
export const getStaticProps = async () => {
const data = await client.get({ endpoint: "XXXXX" });
return {
props: {
XXXXX: data.contents,
},
};
};
XXXXX = APIプレビューで確認できる*****の部分↓
//microCMSのAPIプレビュー画面
client
.get({
endpoint: '*****',
})
.then((res) => console.log(res));
〇〇〇〇〇 = 記事ページのディレクトリ。 ここでは posts を設定する。
① pages/ ディレクトリに posts/ ディレクトリを作成する。
// ~/pages/ に移動している状態で。
mkdir posts
cd $_
② [id].js という名前のファイルを作成し、下記の内容を入力する。
// pages/post/[id].js
import { client } from "../../libs/client";
export default function postId({ post }) {
return (
<main>
<h1>{post.title}</h1>
<p>{post.publishedAt}</p>
<div
dangerouslySetInnerHTML={{
__html: `${post.body}`,
}}
/>
</main>
);
}
// 静的生成のためのパスを指定します
export const getStaticPaths = async () => {
const data = await client.get({ endpoint: "post" });
const paths = data.contents.map((content) => `/posts/${content.id}`);
return { paths, fallback: false };
};
// データをテンプレートに受け渡す部分の処理を記述します
export const getStaticProps = async (context) => {
const id = context.params.id;
const data = await client.get({ endpoint: "post", contentId: id });
return {
props: {
post: data,
},
};
};
Swiper のインストール
yarn add swiper
使用したい場所で下記をインポート。
import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/css';
returnの内使用したい部分に下記を入力。
<Swiper
spaceBetween={50}
slidesPerView={3}
onSlideChange={() => console.log('slide change')}
onSwiper={(swiper) => console.log(swiper)}
>
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide>Slide 3</SwiperSlide>
<SwiperSlide>Slide 4</SwiperSlide>
...
</Swiper>
これで基本的なスライドショーがは完了。 ここでは自動再生と全画面表示したいので、オプションを使用します。
import { Swiper, SwiperSlide } from 'swiper/react';
import { Autoplay, Pagination, Navigation, EffectFade } from "swiper";
import "swiper/css";
import "swiper/css/pagination";
import "swiper/css/navigation";
import "swiper/css/effect-fade";
<Swiper
effect={"fade"}
spaceBetween={30}
centeredSlides={true}
autoplay={{
delay: 2500,
disableOnInteraction: false,
}}
pagination={{
clickable: true,
}}
navigation={true}
modules={[Autoplay, Pagination, Navigation, EffectFade]}
className="mySwiper"
>
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide>Slide 3</SwiperSlide>
<SwiperSlide>Slide 4</SwiperSlide>
<SwiperSlide>Slide 5</SwiperSlide>
<SwiperSlide>Slide 6</SwiperSlide>
<SwiperSlide>Slide 7</SwiperSlide>
<SwiperSlide>Slide 8</SwiperSlide>
<SwiperSlide>Slide 9</SwiperSlide>
</Swiper>
画像のスタイルを設定します↓
// 作業ディレクトリ内で。
cd styles
touch swiper_style.css
_app.js
import "../styles/swiper_style.css";
デプロイの準備
GitHubと連携
リポジトリを作成してプッシュしておく。