🦔

【Next.js】Next.js & Contentful BlogApp 【9CardItem2】

2022/11/25に公開

【9CardItem2】

YouTube:https://youtu.be/Va45g6Os7To

https://youtu.be/Va45g6Os7To

今回は前回作成したカードのコンポーネントに
ContentfulのAPIのデータを反映する部分を実装します。

Next.jsのアプリと画像データが保存されている場所のドメインが異なりますので、
「next.config.js」に追加で設定が必要になります。

pages/index.js
import Head from 'next/head'
import Image from 'next/image'
import { useEffect, useState } from 'react'
import CardItem from '../components/CardItem'
import Hero from '../components/Hero'
import Layout from '../components/Layout'
import styles from '../styles/Home.module.css'
import { client } from '../utils/contentfulClient'

export default function Home() {
  const [items, setItems] = useState([])

  useEffect(() => {
    ;(async () => {
      const res = await client.getEntries({
        content_type: 'myPosts',
      })
      setItems(res.items)
      console.log(res.items)
    })()
  }, [])

  return (
    <Layout>
      <Hero />
      <div className="max-w-7xl flex flex-wrap justify-center mx-auto mb-3 py-2 gap-4">
        {items ? (
          items.map((item) => (
            <div key={item.sys.id}>
              <CardItem item={item} />
            </div>
          ))
        ) : (
          <div className="text-center text-3xl font-black">No Posts...</div>
        )}
      </div>
    </Layout>
  )
}
components/CardItem.js
import Image from 'next/image'

const CardItem = ({ item }) => {
  return (
    <div className="w-96 md:w-64 lg:w-96 p-4 border border-solid border-slate-400 rounded-md bg-white">
      <div className="w-full h-64 relative mb-2 bg-orange-200">
        <Image
          src={`https:${item.fields.image.fields.file.url}`}
          alt={item.fields.image.fields.title}
          fill
          sizes="100%"
          className="object-cover"
        />
      </div>
      <h3 className="font-black text-xl sm:text-xl md:text-base lg:text-xl mb-1">
        {item.fields.title}
      </h3>
      <div>
        <span>{item.sys.createdAt.substring(0, 10)}</span>
      </div>
    </div>
  )
}

export default CardItem
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  images: {
    domains: ['images.ctfassets.net'],
  },
}

module.exports = nextConfig

Discussion