SmartCodingTips

📝 React Todo List

Building a Todo List is a classic React example that helps you understand state management, event handling, and rendering lists dynamically.


⚡ 1. Create a Todo Component


function Todo({ todo, onToggle }) {
  return (
    <li
      onClick={() => onToggle(todo.id)}
      className={`cursor-pointer ${todo.completed ? 'line-through text-gray-500' : ''}`}
    >
      {todo.text}
    </li>
  );
}

🧠 2. Manage State with useState


import { useState } from 'react';

function TodoApp() {
  const [todos, setTodos] = useState([
    { id: 1, text: 'Learn React', completed: false },
    { id: 2, text: 'Build a Todo App', completed: false },
  ]);

  const toggleTodo = (id) => {
    setTodos(
      todos.map(todo => 
        todo.id === id ? {...todo, completed: !todo.completed} : todo
      )
    );
  };

  return (
    <ul>
      {todos.map(todo => 
        <Todo key={todo.id} todo={todo} onToggle={toggleTodo} />
      )}
    </ul>
  );
}

🔧 3. Add New Todos


function TodoApp() {
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState('');

  const addTodo = () => {
    if(input.trim() === '') return;
    setTodos([...todos, { id: Date.now(), text: input, completed: false }]);
    setInput('');
  };

  return (
    <div>
      <input 
        type="text" 
        value={input} 
        onChange={e => setInput(e.target.value)} 
        placeholder="Add a task" 
        className="border p-2 mr-2 rounded"
      />
      <button onClick={addTodo} className="bg-blue-500 text-white px-4 py-2 rounded">Add</button>

      <ul className="mt-4">
        {todos.map(todo => 
          <Todo key={todo.id} todo={todo} onToggle={toggleTodo} />
        )}
      </ul>
    </div>
  );
}

📋 4. Summary

  • ✅ useState for managing todo state
  • ✅ Dynamic rendering of lists using map()
  • ✅ Handling events to toggle and add todos
  • ✅ Reusable Todo component

This Todo App is a foundation for more advanced features like editing, deleting, filtering, and persisting todos using localStorage or APIs.