Todo List App

Step 1: Set Up Your React Project

Open your terminal and run the following commands:

bashCopy codenpx create-react-app todo-list
cd todo-list

Step 2: Create the Todo List Component

Open src/App.js and replace its content with the following code:

javascriptCopy codeimport React, { useState } from 'react';
import './App.css';

const App = () => {
  const [tasks, setTasks] = useState([]);
  const [inputValue, setInputValue] = useState('');

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
  };

  const handleAddTask = () => {
    if (inputValue.trim()) {
      setTasks([...tasks, { text: inputValue, completed: false }]);
      setInputValue('');
    }
  };

  const handleToggleTask = (index) => {
    const newTasks = [...tasks];
    newTasks[index].completed = !newTasks[index].completed;
    setTasks(newTasks);
  };

  const handleDeleteTask = (index) => {
    const newTasks = tasks.filter((_, i) => i !== index);
    setTasks(newTasks);
  };

  return (
    <div className="App">
      <h1>Todo List</h1>
      <input
        type="text"
        value={inputValue}
        onChange={handleInputChange}
        placeholder="Add a new task..."
      />
      <button onClick={handleAddTask}>Add Task</button>
      <ul>
        {tasks.map((task, index) => (
          <li key={index} style={{ textDecoration: task.completed ? 'line-through' : 'none' }}>
            <span onClick={() => handleToggleTask(index)}>{task.text}</span>
            <button onClick={() => handleDeleteTask(index)}>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default App;

Step 3: Style Your App

Open src/App.css and add some basic styles:

cssCopy code.App {
  text-align: center;
  margin: 20px;
  font-family: Arial, sans-serif;
}

input {
  padding: 10px;
  margin-right: 10px;
  width: 200px;
}

button {
  padding: 10px;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0;
}

Step 4: Run Your Application

In the terminal, run:

bashCopy codenpm start

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *