4IT580: Docs
4IT580 WebGithub

2nd Practical Class:
React State Operations

Immutable Array Methods

Such methods produce a new array and do not mutate the existing one.

someArray.map()

someArray.filter()

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

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:

  1. 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 and onChange props
    • call addItem in the form's onSubmit event callback
    • use event.preventDefault() to prevent reloading the page on form submit
  2. implement addItem
    • store current to-do list items using useState
    • use a single object state containing items array and nextId
  3. clear input value on submit
  4. implement setItemCompleted
    • add a new property isCompleted in the item objects
    • use array.map() to update the isCompleted property in one of the items in the list based on its id

Useful Links