
Building A To-Do List App With ReactJS And PHP: A Step-by-Step Guide
In the ever-evolving world of web development, creating interactive and dynamic applications is a key skill. In this tutorial, we'll walk through the process of building a To-Do List application using ReactJS for the frontend and a PHP backend to handle CRUD operations. Follow along to grasp the fundamentals of building a modern web application.
Prerequisites
Before we begin, make sure you have Node.js and npm installed on your machine. Additionally, you'll need a code editor of your choice.
Step 1: Set Up a React App
We'll start by creating a new React app using Create React App. Open your terminal and run the following commands:
npx create-react-app react-todo
cd react-todo
This will set up a new React project named react-todo
.
Step 2: Create Components
In the src
folder, create two components: TodoList.js
and TodoForm.js
. These components will handle displaying the list of tasks and adding new tasks, respectively.
TodoList.js:
import React from 'react';
const TodoList = ({ todos, onEdit, onDelete }) => {
return (
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo}
<button onClick={() => onEdit(index)}>Edit</button>
<button onClick={() => onDelete(index)}>Delete</button>
</li>
))}
</ul>
);
};
export default TodoList;
TodoForm.js
import React, { useState } from 'react';
const TodoForm = ({ onAdd }) => {
const [task, setTask] = useState('');
const handleAdd = (e) => {
e.preventDefault();
if (task.trim() !== '') {
onAdd(task);
setTask('');
}
};
return (
<form onSubmit={handleAdd}>
<input
type="text"
placeholder="Add a new task"
value={task}
onChange={(e) => setTask(e.target.value)}
required
/>
<button type="submit">Add Task</button>
</form>
);
};
export default TodoForm;
Step 3: Create the Main App Component
In src/App.js
, we'll create the main App component. This component will manage the state of our To-Do List and handle CRUD operations.
App.js:
import React, { useState, useEffect } from 'react';
import TodoList from './components/TodoList';
import TodoForm from './components/TodoForm';
const App = () => {
const [todos, setTodos] = useState([]);
useEffect(() => {
fetchTodos();
}, []);
const fetchTodos = async () => {
try {
const response = await fetch('http://localhost:8000/backend.php');
const data = await response.json();
setTodos(data);
} catch (error) {
console.error('Error fetching todos:', error);
}
};
// Add, Edit, and Delete functions go here...
return (
<div>
<h1>React To-Do List</h1>
<TodoForm onAdd={addTodo} />
<TodoList todos={todos} onEdit={editTodo} onDelete={deleteTodo} />
</div>
);
};
export default App;
Step 4: Implement CRUD Operations
Inside App.js
, implement the addTodo
, editTodo
, and deleteTodo
functions to handle CRUD operations. These functions will make API requests to the PHP backend.
App.js (continued):
// ...
const addTodo = async (task) => {
try {
const response = await fetch('http://localhost:8000/backend.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ taskText: task }),
});
const result = await response.json();
if (result.success) {
fetchTodos();
}
} catch (error) {
console.error('Error adding todo:', error);
}
};
const editTodo = async (index, newText) => {
try {
const response = await fetch('http://localhost:8000/backend.php', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ index, newText }),
});
const result = await response.json();
if (result.success) {
fetchTodos();
}
} catch (error) {
console.error('Error editing todo:', error);
}
};
const deleteTodo = async (index) => {
try {
const response = await fetch('http://localhost:8000/backend.php', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ index }),
});
const result = await response.json();
if (result.success) {
fetchTodos();
}
} catch (error) {
console.error('Error deleting todo:', error);
}
};
Step 5: Set Up a PHP Backend
Create a simple PHP file named backend.php
in the root directory of your React app. This file will handle CRUD operations on a JSON file, simulating a backend server.
backend.php:
<?php
$tasksFile = 'tasks.json';
function readTasks() {
global $tasksFile;
if (file_exists($tasksFile)) {
$tasksJson = file_get_contents($tasksFile);
return json_decode($tasksJson, true) ?: [];
}
return [];
}
function writeTasks($tasks) {
global $tasksFile;
$tasksJson = json_encode($tasks, JSON_PRETTY_PRINT);
file_put_contents($tasksFile, $tasksJson);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode(file_get_contents('php://input'), true);
if (isset($data['taskText'])) {
$tasks = readTasks();
$tasks[] = $data['taskText'];
writeTasks($tasks);
echo json_encode(['success' => true]);
exit;
}
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$tasks = readTasks();
echo json_encode($tasks);
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
$data = json_decode(file_get_contents('php://input'), true);
if (isset($data['index']) && isset($data['newText'])) {
$tasks = readTasks();
$index = $data['index'];
if (isset($tasks[$index])) {
$tasks[$index] = $data['newText'];
writeTasks($tasks);
echo json_encode(['success' => true]);
exit;
}
}
}
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
$data = json_decode(file_get_contents('php://input'), true);
if (isset($data['index'])) {
$tasks = readTasks();
$index = $data['index'];
if (isset($tasks[$index])) {
unset($tasks[$index]);
writeTasks(array_values($tasks)); // Reindex the array
echo json_encode(['success' => true]);
exit;
}
}
}
?>
Step 6: Run the Application
Start both the React development server and the PHP server. In two separate terminals, run:
# Start the React development server
npm start
# Start the PHP server
php -S localhost:8000
Visit http://localhost:3000 in your browser to interact with your React To-Do List application.
Conclusion
Congratulations! You've successfully built a To-Do List application using ReactJS and a PHP backend. This tutorial covers the basics of setting up a React app, creating components, implementing CRUD operations, and simulating a backend server.
Feel free to customize and expand upon this example to further enhance your React and web development skills. Happy coding!