0
1

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でアプリ開発記 20250501

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];

//指定した投稿(インデックス)のlikesを1増やす。
    updatedPosts[index].likes += 1;
    
//状態を更新して、再描画を促す。
    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>

//「いいね」ボタン。クリックすると handeLike(index) が呼ばれる。
//post.likes が現在の「いいね数」。
            <button onClick ={() => handleLike(index)}>❤️ いいね ({post.likes})</button>
          </div>
        ))}
      </div>
    </div >
  );
}

export default App;

スクリーンショット 2025-04-30 12.36.28.png

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?