Step-by-Step Coding Our To-Do List App

Step-by-Step Coding Our To-Do List App

Time to code! Open App.js inside src/ and replace its content with the following:

// src/App.js
import React, { useState } from 'react';
import './App.css';

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

  const addTodo = () => {
    if (inputValue.trim() !== "") {
      setTodos([...todos, { text: inputValue, completed: false }]);
      setInputValue("");
    }
  };

  const toggleTodo = (index) => {
    const newTodos = [...todos];
    newTodos[index].completed = !newTodos[index].completed;
    setTodos(newTodos);
  };

  const deleteTodo = (index) => {
    const newTodos = [...todos];
    newTodos.splice(index, 1);
    setTodos(newTodos);
  };

  const editTodo = (index) => {
    const newText = prompt("Edit the todo:", todos[index].text);
    if (newText !== null && newText.trim() !== "") {
      const newTodos = [...todos];
      newTodos[index].text = newText;
      setTodos(newTodos);
    }
  };

  return (
    <div className="App">
      <h1 style={{ color: 'white' }}>My Todo List</h1>
      <div style={{ marginBottom: '20px' }}>
        <input
          type="text"
          placeholder="Add a task..."
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
        />
        <button onClick={addTodo}>Add</button>
      </div>
      <ul>
        {todos.map((todo, index) => (
          <li key={index} style={{
            textDecoration: todo.completed ? 'line-through' : 'none',
            color: todo.completed ? 'gray' : 'white',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            marginBottom: '10px'
          }}>
            <input
              type="checkbox"
              checked={todo.completed}
              onChange={() => toggleTodo(index)}
              style={{ marginRight: '10px' }}
            />
            {todo.text}
            <div>
              <button onClick={() => editTodo(index)}>✏️</button>
              <button onClick={() => deleteTodo(index)}>🗑️</button>
            </div>
          </li>
        ))}
      </ul>
      <footer style={{ marginTop: '30px', color: 'white' }}>
        Created by Jaishree Tomar for <a href="https://www.guvi.in" style={{ color: '#00ffcc' }} target="_blank" rel="noopener noreferrer">GUVI</a>
      </footer>
    </div>
  );
}

export default App;

What this code does:

  • useState([]): Stores the list of todos
  • useState(""): Stores user input as text
  • addTodo(): Adds a task only if input isn’t empty
  • toggleTodo(): Marks a task completed or not
  • editTodo(): Prompts user to update task text
  • deleteTodo(): Removes a task from the list

JSX loops through all todos using map() and displays them as list items with checkboxes and action buttons.