I have a TodoItem
component that looks like this:
type Todo = {
id: string;
text: string;
isCompleted: boolean;
createdAt: string;
};
type TodoProps = {
todo: Todo;
removeTodo: (id: string) => void;
markCompletedTodo?: (id: string) => void;
};
const TodoItem = ({ todo, removeTodo, markCompletedTodo }: TodoProps) => {
return (
<div>
<h2>{todo.text}</h2>
<button type="button" onClick={() => removeTodo(todo.id)}>
Remove
</button>
{typeof markCompletedTodo === 'undefined' ? null : (
<button type="button" onClick={() => markCompletedTodo(todo.id)}>
Mark completed
</button>
)}
</div>
);
};
export default TodoItem;
As you can see, it gets a todo
with a isCompleted
property. I want to render the 'Mark completed' button only is the isCompleted
property is false
, but currently I'm checking for the optional markCompletedTodo
prop. That works but I have the feeling this can be done in a better way.
I'm using it to create two lists of TODOS, one for incomplete TODOS and one for complete TODOS, so I'm using it like this in another component:
return (
<h2>Incomplete TODOS</h2>
{incompleteTodos.map((todo) => (
<TodoItem
key={todo.text}
todo={todo}
removeTodo={removeTodoRequest}
markCompletedTodo={markCompletedTodoRequest}
/>
))}
<h2>Complete TODOS</h2>
{completeTodos.map((todo) => (
<TodoItem
key={todo.text}
todo={todo}
removeTodo={removeTodoRequest}
/>
))}
)
Is there a better approach to this regarding the type checking and the prop types in the TodoItem
component, or any other aspect?