Created
March 9, 2019 05:39
-
-
Save asleepysamurai/c814bdaeff6ccb2278512f6b0fa3a487 to your computer and use it in GitHub Desktop.
TodoItem getDerivedStateFromProps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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