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?

ChatGPTでアプリ開発記 20250502

Posted at

投稿削除ボタンを追加

import React, { useState } from 'react';

function App() {
  const [text, setText] = useState('');
  const [posts, setPosts] = useState([]);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (text.trim() === '') return;

    const now = new Date();
    const formattedTime = now.toLocaleString('ja-JP', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });


    const newPost = {
      text: text,
      time: formattedTime,
      likes: 0
    };

    setPosts([newPost, ...posts])
    setText('');
  };

  const handleLike = (index) => {
    const updatedPosts = [...posts];
    updatedPosts[index].likes += 1;
    setPosts(updatedPosts);
  }

//handleDelete という名前の関数を定義し、引数として index を受け取ります。
//これは、削除したい投稿が posts 配列の中で何番目か(0から始まる番号)取得する為です。
  const handleDelete = (index) => {

//posts.filter(...) は、posts 配列から特定の要素を除いた新しい配列を作ります。
//(_, i):
//最初の引数 _ は各投稿の中身(ここでは使わないので _ にしている)。
//2番目の引数 i はインデックス番号(投稿が配列の何番目か)です。
//i !== index:
//今のループ中の投稿の i が、削除したい index と一致しないものだけを残します。
//つまり、「削除したい投稿以外を全部残す」ことで、削除された状態の配列を作ります。
    const updatedPosts = posts.filter((_, i) => i !== index);

    setPosts(updatedPosts);
  }

  return (
    <div style={{ padding: '2rem', fontFamily: 'sans-serif' }}>
      <h1>SNS</h1>
      <form onSubmit={handleSubmit}>
        <textarea
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder="今なにしてる?"
          rows="4"
          cols="50"
          style={{ display: 'block', width: '100%', marginBottom: '1rem' }}
        />
        <button type="submit">投稿する</button>
      </form>

      <div style={{ marginTop: '2rem' }}>
        <h2>投稿一覧</h2>
        {posts.map((post, index) => (
          <div key={index} style={{ padding: '1rem', borderBottom: '1px solid #ccc' }}>
            <div style={{ fontSize: '0.8rem', color: '#666' }}>{post.time}</div>
            <div>{post.text}</div>
            <button onClick ={() => handleLike(index)}>❤️ いいね ({post.likes})</button>
            
//クリックされたときに、現在の投稿の index を使って handleDelete 関数を呼び出します
            <button onClick={() => handleDelete(index)} style={{ marginleft: '1rem', color: 'red'}}>
              🗑️ 削除</button>
          </div>
        ))}
      </div>
    </div >
  );
}

export default App;

ezgif.com-video-to-gif-converter.gif

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?