Inteview question on Todo-App with following Requirements:
Create a todo react app
requirements:
user should be able to add a todo
todo should be listed on dom
user should be able to update status of a todo
user should be able to edit the text
user should be able to delete a todo
import { useState } from 'react';
import './App.css';
function App() {
const [toDoValue, setToDoValue] = useState('');
const [toList, setToList] = useState([]);
const handleAdd = () => {
let newItem = { id: toList.length + 1, label: toDoValue, completed: false };
let newArray = [...toList, newItem];
setToList(newArray);
setToDoValue('');
};
const handleValueChange = (id, newValue) => {
let result = toList.filter((item) => item.id !== id);
let output = [...result, { id: id, label: newValue, completed: false }];
setToList(output);
};
const handleDelete = (id) => {
let result = toList.filter((item) => item.id !== id);
setToList(result);
};
const handleIsCompleted = (id) => {
// handleIsCompleted logic
let result = toList.map((item) => {
if (item.id === id) {
return { ...item, completed: !item.completed };
} else {
return item;
}
});
setToList(result);
};
return (
<>
<input
type="text"
value={toDoValue}
onChange={(e) => setToDoValue(e.target.value)}
placeholder="Enter To Do value"
/>
<button onClick={handleAdd}>Add</button>
{toList?.map((item) => {
return (
<div key={item.id}>
<input
disabled={item.completed}
value={item.label}
onChange={(e) => handleValueChange(item.id, e.target.value)}
/>
<button onClick={() => handleIsCompleted(item.id)}>
{item.completed ? 'Mark as Incomplete' : 'Mark as Completed'}
</button>
<button onClick={() => handleDelete(item.id)}>Delete</button>
</div>
);
})}
</>
);
}
export default App;
This is my approach to do in limit time of 30mins. You can think of much better.
Top comments (0)