Step 13

Let's filter the meetings based on the search query.

We will use two NPM packages, escape-string-regexp and sort-by, to help us with this.

Stop the app and install the packages.

npm install escape-string-regexp sort-by

Import these packages in the ListMeetings component:

import escapeRegExp from "escape-string-regexp";
import sortBy from "sort-by";

Update the ListMeetings.render method:

render() {
  const query = this.state.query.trim();
  let meetings = [];
  if (query) {
    const match = new RegExp(escapeRegExp(query), "i");
    meetings = this.props.meetings.filter(
      (m) =>
        match.test(m.course) || match.test(m.instructor) || match.test(m.time)
    );
  } else {
    meetings = this.props.meetings;
  }

  meetings.sort(sortBy("course"));

  return (
    <div className="list-meetings">
      <div className="list-meetings-top">
        <Search query={this.state.query} updateQuery={this.updateQuery} />
      </div>
      <ol className="meeting-list">
        {meetings.map((meeting, index) => (
          <Meeting
            meeting={meeting}
            key={index}
            onDeleteMeeting={this.props.onDeleteMeeting}
          />
        ))}
      </ol>
    </div>
  );
}

Save the file and view the app in the browser. Type in a query in the search bar!

Read this to understand the code better!

The following statement simply sorts the meetings by the "course" attribute.

meetings.sort(sortBy("course"));

The sort method sorts the elements of an array in place and returns the sorted array. It optionally takes in a function that defines the sort order. This is what sortBy does for us. I have used it to sort the "meeting" objects based on "course" attribute. The sort-by package more generally allows for sorting by multiple properties.

The following code snippet

const match = new RegExp(escapeRegExp(query), "i");
meetings = this.props.meetings.filter(
  (m) =>
    match.test(m.course) || match.test(m.instructor) || match.test(m.time)
);

We create a "Regular Expression" (regex) object and use that to test if the search query matches information about a meeting.

The regex will not work correctly when a user input (search query) contains inputs such as ? or * because those inputs have special meaning in a regex expression. The escapeRegExp helps us to circumvent this potential issue.

Regular expressions are too complex to get into in this program, but they're incredibly valuable in programming to verify patterns.

Check out what MDN has to say about Regular Expressions. Also, check out how the String .match() method uses Regular expressions to verify patterns of text.