Your mission is to refactor the code below so that none of the descendant components have more privilege than they need to accomplish these tasks.
Acceptance Criteria:
The CreateNewTodo component should only be able to modify the state in one specific way: to add a new todo to the list
The TodoList component should only be able to modify the state in two specific ways: toggling a todo between complete/incomplete, and deleting a todo.
Code Playground
importReactfrom'react';
importCreateNewTodofrom'./CreateNewTodo';
importTodoListfrom'./TodoList';
functionApp(){
const[todos,setTodos] = React.useState([]);
return(
<divclassName="wrapper">
<divclassName="list-wrapper">
<TodoListtodos={todos}setTodos={setTodos}/>
</div>
<CreateNewTodosetTodos={setTodos}/>
</div>
);
}
exportdefaultApp;
Solution:
In this video, I share my solution, but also a pretty important takeaway near the end. There's another benefit to structuring things this way.
Before, our business logic was sprinkled throughout the application, mixed in with the JSX at the extremities of our application, within CreateNewTodo and TodoList.
Now, though, we've centralized this logic in three handy functions, grouped together:
functionApp(){
const[todos, setTodos]=React.useState([]);
functionhandleCreateTodo(value){
...
}
functionhandleToggleTodo(id){
...
}
functionhandleDeleteTodo(id){
...
}
return(
<divclassName="wrapper">
...
</div>
);
}
Imagine you're brand-new to this codebase. Which version do you think is easier for you to make sense of?