4.14 components control vs non control and components without state vs with state

In this lesson we tidy up ExpenseItem and start preparing the next feature: filtering. Open ExpenseItem.js and select every const declaration after const ExpenseItem = (props) => { down to the return statement, then delete them. What stays is only the function signature with its props parameter and the return block.

Because we removed the local constants, the title is no longer defined as a variable. Replace its usage in the JSX with {props.title} so the component keeps reading the value coming from the parent through props.

Creating the filter component

  • Create a new file ExpensesFilter.js inside the components folder.
  • Create a matching ExpensesFilter.css next to it.
  • Pause the video and copy the provided JS and CSS code into the two files.

Take a moment to recall the JavaScript filter method we will use in the upcoming lessons. The general idea of a filter is to take input, process it according to a rule and produce a new output containing only the items that satisfy that rule. In JavaScript, Array.prototype.filter follows the same idea: it returns a brand-new array containing only the elements of the original array for which the predicate function returns true.

const filtered = expenses.filter((expense) => {
  return expense.date.getFullYear().toString() === selectedYear;
});

That is exactly the mechanism we will rely on in the next lessons to display only the expenses matching a given year. For now, just keep in mind what filter does — we will use it more often very soon. See you in the next class.