Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

searchWords.filter is not a function

  • I am using react-highlight-words package to highlight the text entered in the textbox
  • I referred react-highlight-words documenation in that they are passing searchWords as an array. https://www.npmjs.com/package/react-highlight-words
  • but the problem is when I pass it an array let searchBarText = []; I am facing an error searchWords.filter is not a function.
  • Can you tell me how to fix it, so that in future I will fix it myself.
  • Providing my sandbox and code snippet below.

https://codesandbox.io/s/00nm6k8orp

class SearchBar extends React.Component {
  constructor() {
    super();
    this.state = {
      // testHighlight: {}
      testHighlight: []
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    console.log(e.target.value); // your search bar text
    let object = document.getElementById("myDiv");
    console.log(object.textContent); // your div text

    // now that you have the two strings you can do your search in your favorite way, for example:
    let searchBarText = [];
    searchBarText = e.target.value;
    console.log("searchBarText --->", searchBarText);

    let divText = object.textContent;
    console.log("divText --->", divText);

    if (divText.includes(searchBarText)) {
      console.log("the div text contains your search text");
    } else {
      console.log("the div text doesn't contain search text");
    }

    // this.setState({ testHighlight: response.data });

    this.setState({ testHighlight: searchBarText });
  }

  render() {
    return (
      <div>
        <input
          type="text"
          className="input"
          onChange={this.handleChange}
          placeholder="Search..."
          // highlightText={this.handleChange}
          testHighlight={this.state.testHighlight}
        />

        <HighlighterImplementation testHighlight={this.state.testHighlight} />
      </div>
    );
  }
}

1 Answers

In the SearchBar.js file you are updating the testHighlight to a string:

this.setState({ testHighlight: searchBarText });

Didn't you mean to do:

 this.setState({ testHighlight: [searchBarText] });

Or if you want to add it to the existing array:

this.setState({ testHighlight: [...this.state.testHighlight, searchBarText] });
like image 136
Sagiv b.g Avatar answered Sep 07 '26 12:09

Sagiv b.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!