In this lesson, let's add the Delete button to our table.
Delete Button
Here's what we have in the Controller:
app/Http/Controllers/TaskController.php:
public function destroy(Task $task){ $task->delete(); return redirect()->route('tasks.index');}
Since we have Route::resource()
here, the React component should fire a DELETE request to the route /tasks/{ID}
.
So, first, we define the function inside the React component.
resources/js/pages/Tasks/Index.tsx:
import { Head } from '@inertiajs/react'; import { Head, router } from '@inertiajs/react'; // ... export default function Index({ tasks }: { tasks: Task[] }) { const deleteTask = (id: number) => { if (confirm('Are you sure?')) { router.delete(route('tasks.destroy', { id })); } }; // ...
Then, we need to add a Button to the table that calls the deleteTask()
method.
The Shadcn Button component is already installed in the starter kit, so we don't need to run any npx
commands. We just need to import it with button variants.
We add a new <TableCell>
to our <TableRow>
.
resources/js/pages/Tasks/Index.tsx:
import { Button, buttonVariants } from '@/components/ui/button'; // ... {tasks.map((task) => ( <TableRow key={task.id}> <TableCell>{task.name}</TableCell> <TableCell className={task.is_completed ? 'text-green-600' : 'text-red-700'}> {task.is_completed ? 'Completed' : 'In Progress'} </TableCell> <TableCell className="flex flex-row gap-x-2 text-right"> // [tl! add:start] <Button variant={'destructive'} className={'cursor-pointer'} onClick={() => deleteTask(task.id)}> Delete </Button> </TableCell> // [tl! add:end] </TableRow>))}
Here's the visual result:
Now, see that variant={'destructive'}
? To see what other button variants are available, look at...