2
2

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】

Posted at

注意

あらかじめ言っておきますが、筆者は初心者なので、自分なりの解釈でまとめています。「100%信じるぜ!」という気持ちで読まないようお願いします。どうぞよろしく!

参考

経緯

nextjs,typescript,supabaseを使用して、ポートフォリオを作成しているのですが、よく使用するものがあったので、備忘録として残します

以下の様なケースを想定します。
「献立を追加」ボタンを押下したら、献立カードが1つ増えるといったケースです。

スクリーンショット 2025-05-26 9.01.35.png

前提

type MenuItemsType = {
  id: number,
  date: Date,
  meal: {
    breakfast: string,
    lunch: string,
    dinner: string
  }
}

export default function Home() {
  const [menuSchedule, setMenuSchedule] = useState<MenuItemsType[]>([{
    id: new Date().getTime(),
    date: new Date,
    meal: {
      breakfast: '',
      lunch: '',
      dinner: '',
    }
  }])

return (
{menuSchedule.map((menuList, index) => (...

現在、menuScheduleには、空のデータが入っているので、カードは空白の状態が表示されます。

方法

増やす

配列を map で回してカードを表示しているため、同じ形式の空オブジェクトを追加すれば、カードが増える仕組みになります。

const onEmptyMenuAddButtonClicked = () => {
  const newMenu = {
    id: new Date().getTime(), // 一意なID(タイムスタンプ)
    date: new Date(),
    meal: {
      breakfast: '',
      lunch: '',
      dinner: '',
    }
  }
  setMenuSchedule([...menuSchedule, newMenu])
}

消去

filterを使用すれば良いです。filterは、条件に一致したものを返します。

const onMenuDeleteButtonClicked =(id:number)=> {
    const updated = menuSchedule.filter(menu => menu.id !== id)
    setMenuSchedule(updated)  
};

感想

これは、nextjsやreactでよく使用する方法だと思いますので、覚えます。
ガンガンアプリ開発していこう

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?