tommy123
tommy123

Reputation: 587

How to stop my search function from checking cases (Uppercase/lowercase) - Javascript/ReactJS

I am working on a search function in ReactJS. My search function is working fine , but it is checking cases(Uppercase/lowercase). This is my Demo Fiddle. You can check the search functionality. I want to get rid of the case checking(Uppercase/lowercase). How should I change the code in the easiest manner?

This is my Search function

getMatchedList(searchText) {
    console.log('inside getMatchedList');
    if (searchText === ''){
      this.setState({ data: this.state.dataDefault });
    }
    if (!TypeChecker.isEmpty(searchText)) {//Typechecker is a dependency
      console.log('inside if block');
      const res = this.state.dataDefault.filter(item => {
        return item.firstName.includes(searchText) || item.lastName.includes(searchText);
      });
      console.log('res' + JSON.stringify(res));

      this.setState({ data: res });
    }
  }

If I remove Typechecker dependency, how should I change the code? I basically want my search function to be case case insensitive

Upvotes: 2

Views: 1700

Answers (2)

quirimmo
quirimmo

Reputation: 9988

With ReactTable you can filter out directly through the table props.

When you define your table accessors, you can define them in the following way:

{
  Header: "Name",
  columns: [
    {
      Header: "First Name",
      accessor: "firstName",
      filterMethod: (filter, row) =>
      row[filter..toUpperCase().includes(filter.value.toUpperCase())
    },
    {
      Header: "Last Name",
      id: "lastName",
      accessor: "lastName",
      filterMethod: (filter, row) => row[filter.id].toUpperCase().includes(filter.value.toUpperCase())
     }
   ]
 },

As you can see the filterMethod will do the filter for you.

And then, you can completely remove your getMatchedList function (so you get rid also of TypeChecker as you want to).

The case insensitive is made checking the values using toUpperCase() (you can even use toLowerCase()) which will give you the case insensitive.

Here your fork:

https://codesandbox.io/s/w0x6wwpo15

Upvotes: 1

aseferov
aseferov

Reputation: 6393

You can use toLowerCase

if (!TypeChecker.isEmpty(searchText)) {
  console.log("inside if block");
  const res = this.state.dataDefault.filter(item => {
    if (
      item.firstName.toLowerCase().includes(searchText.toLowerCase()) ||
      item.lastName.toLowerCase().includes(searchText.toLowerCase())
    )
      return item;
  });
  console.log(res);

  this.setState({ data: res });
}

https://codesandbox.io/s/5yj23zmp34

Upvotes: 1

Related Questions