Skip to content

Instantly share code, notes, and snippets.

@asleepysamurai
Created March 9, 2019 05:39
Show Gist options
  • Save asleepysamurai/c814bdaeff6ccb2278512f6b0fa3a487 to your computer and use it in GitHub Desktop.
Save asleepysamurai/c814bdaeff6ccb2278512f6b0fa3a487 to your computer and use it in GitHub Desktop.
TodoItem getDerivedStateFromProps
/**
* TodoItem Component
*/
import React, { useState, useCallback } from 'react';
function TodoItem({
id,
text,
toggleItemCompleted,
completedItemIds
}) {
const [completed, setCompleted] = useState(false);
const todoItemIndexInCompletedItemIds = completedItemIds.indexOf(id);
const isCompleted = todoItemIndexInCompletedItemIds > -1;
if (isCompleted !== completed) {
setCompleted(isCompleted);
}
const onToggle = useCallback(() => {
toggleItemCompleted(id);
}, [toggleItemCompleted, id]);
return (
<div
className="todo-item">
<input
id={`completed-${id}`}
type="checkbox"
onChange={onToggle}
checked={completed} />
<label>{text}</label>
</div>
);
};
export default TodoItem;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment