💬

【Next.js】基礎から始めるNext.js API Routes【13UserCard】

2022/12/22に公開

【13UserCard】

YouTube: https://youtu.be/lJH5bbQvkIo

https://youtu.be/lJH5bbQvkIo

今回はユーザーのリストを「Flowbite」のカードコンポーネントを使用して
表示する部分の実装を行います。

pages/index.tsx
import { useEffect, useState } from 'react'
import Layout from '../components/Layout'
import { User } from '@prisma/client'
import UserCard from '../components/UserCard'

export default function Home() {
  const [users, setUsers] = useState<Pick<User, 'id' | 'email' | 'name'>[]>([])

  useEffect(() => {
    ;(async () => {
      const res = await fetch('/api/users')
      const users = await res.json()
      setUsers(users)
      console.log(users)
    })()
  }, [])

  return (
    <Layout>
      <div className="flex flex-col justify-center items-center">
        <h2 className="text-4xl font-black font-sans p-4 mt-6">User Lists</h2>
        <div className="flex flex-wrap w-full justify-center items-center gap-3">
          {users && users.map((user) => <UserCard key={user.id} user={user} />)}
        </div>
      </div>
    </Layout>
  )
}
components/UserCard.tsx
import { Card } from 'flowbite-react'
import { CheckBadgeIcon } from '@heroicons/react/24/solid'
import { User } from '@prisma/client'
import { FC } from 'react'

interface Props {
  user: Pick<User, 'id' | 'email' | 'name'>
}

const UserCard: FC<Props> = ({ user }) => {
  return (
    <div className="w-60">
      <Card>
        <div className="flex flex-col items-center pb-10">
          <CheckBadgeIcon className="mb-3 h-24 w-24 rounded-full shadow-lg" />
          <h5 className="mb-1 text-xl font-medium text-gray-900 dark:text-white">
            {user.name}
          </h5>
          <span className="text-sm text-gray-500 dark:text-gray-400">
            {user.email}
          </span>
          <div className="mt-4 flex space-x-3 lg:mt-6">
            <a
              href="#"
              className="inline-flex items-center rounded-lg bg-blue-700 py-2 px-4 text-center text-sm font-medium text-white hover:bg-blue-800 focus:outline-none focus:ring-4 focus:ring-blue-300 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
            >
              Add friend
            </a>
          </div>
        </div>
      </Card>
    </div>
  )
}

export default UserCard

Discussion