2nd Practical Class:
React State Operations
- immutable array methods
- immutable operations with objects and arrays
- custom hooks
Immutable Array Methods
Such methods produce a new array and do not mutate the existing one.
someArray.map()
- transforms array items into a new array
someArray.filter()
- filters out some items from an array based on a condition
JavaScript Spread Operator
Combine multiple objects or arrays together.
Spread is when ...
is on the right side of =
operator.
Spread for Objects
Spread for Arrays
JavaScript Rest Operator
Get the remainder of object properties or array elements after getting specific elements.
Rest is when ...
is on the left side of =
operator.
Rest for Objects
Rest for Arrays
Custom Hooks in React
It is possible to extract some stateful logic into a separate hook (a function whose name begins with use
).
Advantages
- encapsulation of logic
- better separation of concerns
- reusability
- clear API
To-do List
There is a sample to-do list page:
frontend/src/modules/static-pages/Practical02Page.js
It uses a custom hook useTodoList
which exposes the items
array and several actions for manipulating the list of items.
What will be done at the class:
- convert 'add item' input & button into a form which can be submitted
- store the current input value using
useState
- bind the input value to the state using
value
andonChange
props - call
addItem
in the form'sonSubmit
event callback - use
event.preventDefault()
to prevent reloading the page on form submit
- store the current input value using
- implement
addItem
- store current to-do list items using
useState
- use a single object state containing
items
array andnextId
- store current to-do list items using
- clear input value on submit
- implement
setItemCompleted
- add a new property
isCompleted
in the item objects - use
array.map()
to update theisCompleted
property in one of the items in the list based on itsid
- add a new property
- Final state: practical-02-end