Files
ballistic-builder/src/components/Brand/brand.tsx

92 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-11-21 15:24:37 -05:00
"use client";
import { ChangeEvent, FC, useState } from "react";
import { brandType } from "../../types/brandType";
interface Props {
brand: brandType;
changeBrandName: (id: number, name: string) => void;
deleteBrand: (id: number) => void;
}
const Brand: FC<Props> = ({
brand,
changeBrandName,
deleteBrand,
}) => {
// State for handling editing mode
const [editing, setEditing] = useState(false);
// State for handling text input
const [name, setName] = useState(brand.name);
// Event handler for text input change
const handleNameChange = (e: ChangeEvent<HTMLInputElement>) => {
setName(e.target.value);
};
// Event handler for initiating the edit mode
const handleEdit = () => {
setEditing(true);
};
// Event handler for saving the edited text
const handleSave = async () => {
changeBrandName(brand.id, name);
setEditing(false);
};
// Event handler for canceling the edit mode
const handleCancel = () => {
setEditing(false);
setName(brand.name);
};
// Event handler for deleting a todo item
const handleDelete = () => {
if (confirm("Are you sure you want to delete this brand?")) {
deleteBrand(brand.id);
}
};
// Rendering the Todo component
return (
<div className="flex items-center gap-2 p-4 border-gray-200 border-solid border rounded-lg">
{/* Checkbox for marking the todo as done */}
{/* Input field for brand text */}
<input
type="text"
value={name}
onChange={handleNameChange}
readOnly={!editing}
className="outline-none read-only:border-transparent focus:border border-gray-200 rounded px-2 py-1 w-full"
/>
{/* Action buttons for editing, saving, canceling, and deleting */}
<div className="flex gap-1 ml-auto">
{editing ? (
<button
onClick={handleSave}
className="bg-green-600 text-green-50 rounded px-2 w-14 py-1"
>
Save
</button>
) : (
<button
onClick={handleEdit}
className="bg-blue-400 text-blue-50 rounded w-14 px-2 py-1"
>
Edit
</button>
)}
{editing ? (
<button
onClick={handleCancel}
className="bg-red-400 w-16 text-red-50 rounded px-2 py-1"
>
Close
</button>
) : (
<button
onClick={handleDelete}
className="bg-red-400 w-16 text-red-50 rounded px-2 py-1"
>
Delete
</button>
)}
</div>
</div>
);
};
export default Brand;