React - Computed Properties

0 votes
111 views
added Oct 22, 2019 in React by LC Marshal Captain (25,770 points)

If the computation is short and simple, just put it in render, else move it out of the component and place it in function.

Below, is the example of product filter and sort to show-only new item, sorted by price.

function newItemsCheapestFirst(items) {
  return items
    .filter(item => item.isNew)
    .sort((a, b) => {
      if(a.price < b.price) {
        return -1;
      } else if(a.price > b.price) {
        return 1;
      } else {
        return 0;
      }
    });
}

function NewItemsList({ items }) {
  return (
    <ul>
      {newItemsCheapestFirst(items).map(item =>
        <li key={item.id}>{item.name}, ${item.price}</li>
      )}
    </ul>
  );
}

For working playground, go here: https://1oz6vp66y4.csb.app/

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...