Home > Article > Web Front-end > Todo list in react js
Follow me on LinkedIn
Follow me on Github.com
Click & Read
This simple Todo List app is a great starting point for beginners to get familiar with React's fundamentals, including state management, event handling, and rendering lists.
Before you start, make sure you have Node.js and npm (or yarn) installed on your machine. You can create a new React project using Create React App.
Open your terminal or command prompt and run the following command to create a new React project:
npx create-react-app todo-list
Navigate to the project directory:
cd todo-list
Replace the contents of src/App.js with the following code:
import React, { useState } from 'react'; import './App.css'; function App() { const [todos, setTodos] = useState([]); const [input, setInput] = useState(''); const handleInputChange = (e) => { setInput(e.target.value); }; const handleAddTodo = () => { if (input.trim()) { setTodos([...todos, { text: input, completed: false }]); setInput(''); } }; const handleToggleComplete = (index) => { const newTodos = todos.map((todo, i) => { if (i === index) { return { ...todo, completed: !todo.completed }; } return todo; }); setTodos(newTodos); }; const handleDeleteTodo = (index) => { const newTodos = todos.filter((_, i) => i !== index); setTodos(newTodos); }; return ( <div className="App"> <header className="App-header"> <h1>Todo List</h1> <div> <input type="text" value={input} onChange={handleInputChange} placeholder="Add a new todo" /> <button onClick={handleAddTodo}>Add</button> </div> <ul> {todos.map((todo, index) => ( <li key={index}> <span style={{ textDecoration: todo.completed ? 'line-through' : 'none', }} onClick={() => handleToggleComplete(index)} > {todo.text} </span> <button onClick={() => handleDeleteTodo(index)}>Delete</button> </li> ))} </ul> </header> </div> ); } export default App;
Modify the src/App.css file to add some basic styling:
.App { text-align: center; } .App-header { background-color: #282c34; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: calc(10px + 2vmin); color: white; } input { padding: 10px; margin-right: 10px; font-size: 16px; } button { padding: 10px; font-size: 16px; cursor: pointer; } ul { list-style-type: none; padding: 0; } li { display: flex; justify-content: space-between; align-items: center; padding: 10px; margin: 10px 0; background-color: #444; border-radius: 5px; } li span { cursor: pointer; }
Now, you can run your Todo List app with the following command:
npm start
This command starts the development server and opens your new React application in your default web browser.
Happy Coding !
The above is the detailed content of Todo list in react js. For more information, please follow other related articles on the PHP Chinese website!