0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React】 #7 年齢計算機アプリを作成

Posted at

はじめに

現在、Reactを習得するために、23種類のReactアプリ開発に取り組んでいます。
今回はその第7弾として、Reactで年齢計算機アプリを作成しました。

要件

一般的な年齢計算機アプリの仕様を満たすことを目標にしました。
具体的には、以下の要件を満たすことを目指しています:

  • ユーザが「西暦」「和暦」及び「誕生月」「誕生日」を入力して年齢を算出
  • 「小学校」「中学校」「高校」「4年生大学」卒業年を表示

作成したアプリのイメージ

アプリ紹介動画

利用技術

  • React
  • Vite
  • TypeScript
  • Tailwind CSS
  • date-fns

意識したポイント

日付計算はdate-fnsを利用

年齢計算はdate-fnsのライブラリを採用しました。
日付の比較、計算などが直感的にわかりやすいので、使いやすかったです。

ageUtils.ts
import { differenceInCalendarYears, isBefore } from "date-fns";

export const calculateAge =  (today: Date ,birthDate: Date): { age: number; countAge: number } => {
   const countAge = differenceInCalendarYears(today, birthDate);

   const birthDateThisYear = new Date(today.getFullYear(), birthDate.getMonth(), birthDate.getDate());
   const age = countAge - (isBefore(today, birthDateThisYear) ? 1 : 0);

   return {age, countAge};
}

useActionStateを使用

前回同様にstateの保持をReact19のuseActionStateを利用しました。
アクション実行時に自動的にステートと実行状態を更新してくれるので、
非常に便利です。

AgeCalc.tsx
  const [state, formAction, pending] = useActionState(
    calcurateAge,
    initialState
  );

  return (
    <main className="flex flex-col justify-start items-center constainer mx-auto px-8 md:px-16 lg:px-24 my-24 gap-4">
      <AgeCalcForm formAction={formAction} pending={pending} error={state.error} />
actions.ts
export async function calcurateAge(
  prevState: State,
  formData: FormData
): Promise<State> {
   const era = formData.get("era") as string;
   const year = formData.get("year");
   const month = formData.get("month") as string;
   const day = formData.get("day") as string;

   ...
}

Github

GitHubにコードをアップロードしていますので、よかったら確認してみてください。
https://github.com/yasi1989/react-age-calc

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?