1
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で作るTodoアプリ①

Posted at

全体コード

import { useState } from 'react';
import './App.css';

function App() {
  const [todos, setTodos] = useState([]);

  function handleAddTodo(todo) {
    setTodos(prev => [...prev, todo]); // 状態(state: todos)を更新
  }

  return (
    <div>
      <h1>Todoリスト</h1>
      <TodoForm onAddTodo={handleAddTodo} />
      <TodoList todos={todos} />
    </div>
  );

  function TodoForm({ onAddTodo }) {
  const [text, setText] = useState('');

  function handleClick() {
    const todo = { text, id: Date.now() };
    onAddTodo(todo); // 配列にtodoオブジェクトを保存
    setText('');
  }

  return (
    <div>
      <input
        type="text"
        placeholder="ここに入力してください"
        value={text}
        onChange={e => {
          setText(e.target.value);
        }}
        onKeyDown={e => {
          if (e.key === 'Enter') handleClick();
        }}
      />
      <button onClick={handleClick}>追加</button>
    </div>
  );
}

function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(({ text, id }) => {
        if (!text.trim()) return; // 空文字ブロック
        return <li key={id}>{text}</li>;
      })}
    </ul>
  );
}

export default App;

機能

・タスクの追加ボタン

ソースコード

リポジトリはこちら

まとめ

タスク入力をユーザーから受け取って、それをレンダリングするところまで実装しています。

リストをmap()などで複数作るときは、それぞれにidなどを持たせて、React側にそれぞれ独立していると認識させなければReactに怒られることを学びました。

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