<div id="app"></app>
const { useState, useReducer } = React;

const initialState = [
  { id: 1, title: "テスト1" },
  { id: 2, title: "テスト2" }
];

const reducer = (state, action)  => {
  switch(action.type) {
    case "ADD":
      return [...state, { id: action.payload.id, title: action.payload.title }];
    case "UPDATE":
      return state.map(item => item.id === action.payload.id ?
        { ...item, title: action.payload.title } : item
      );
    case "DELETE":
      return state.filter(item => item.id !== action.payload.id);
    default:
      throw new Error();
  }
};

const Todo = () => {
  const [title, setTitle] = useState("");
  const [todos, dispatch] = useReducer(reducer, initialState);

  return (
    <>
      <input value={title} onChange={e => setTitle(e.target.value)}/>
      <button
        onClick={() => {
          dispatch({ 
            type: "ADD", 
            payload: { 
              id: todos.length ? todos.slice(-1)[0].id + 1 : 1, 
              title: title 
            }
          });
          setTitle("");
        }}
      >
        ADD
      </button>
      {todos.map(todo => 
        <p key={todo.id}>
          <span>ID:{todo.id} </span>
          <input 
            value={todo.title} 
            onChange={e => dispatch(
              { type: "UPDATE", payload: { id: todo.id, title: e.target.value } }
            )}
          />
          <button 
            onClick={() => dispatch({ type: "DELETE", payload: { id: todo.id } })}
          >
            DELETE
          </button>
        </p>
      )}
    </>
  );
};

ReactDOM.render(<Todo />, document.getElementById('app'));
View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://unpkg.com/react@17/umd/react.development.js
  2. https://unpkg.com/react-dom@17/umd/react-dom.development.js