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;