import React, { useState, useMemo } from
'react'
;
const
SearchBar = ({ searchValue, setSearchValue }) => {
const
handleChange = (e) => {
setSearchValue(e.target.value);
};
return
(
<input
type=
"text"
placeholder=
"Search..."
value={searchValue}
onChange={handleChange}
/>
);
};
const
TodoList = React.memo(({ todos }) => {
return
(
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
});
const
App = () => {
const
[todos, setTodos] = useState([
{ id: 1, text:
'Buy groceries'
},
{ id: 2, text:
'Walk the dog'
},
{ id: 3, text:
'Do laundry'
},
]);
const
[searchValue, setSearchValue] = useState(
''
);
const
[newTask, setNewTask] = useState(
''
);
const
filteredTodos = useMemo(
() =>
todos.filter((todo) =>
todo.text.toLowerCase().includes(searchValue.toLowerCase())
),
[todos, searchValue]
);
const
handleAddTask = () => {
if
(newTask.trim() !==
''
) {
const
newTodo = {
id: Date.now(),
text: newTask.trim(),
};
setTodos([...todos, newTodo]);
setNewTask(
''
);
}
};
return
(
<
div
>
<SearchBar searchValue={searchValue} setSearchValue={setSearchValue} />
<TodoList todos={filteredTodos} />
<
div
>
<input
type=
"text"
placeholder=
"Add task..."
value={newTask}
onChange={(e) => setNewTask(e.target.value)}
/>
<button onClick={handleAddTask}>Add Task</button>
</
div
>
</
div
>
);
};
export
default
App;