searchWords.filter is not a function

Viewed 399
  • 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>
    );
  }
}
2 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] });

Your state 'testHighlight' is being saved as a string and 'HighlighterImplementation' component needs the 'testHighlight' as an array.

So, while setting the state as a prop, you should change that state in an array. split() method can change the string to an array of strings.

You have added searchBarText initial state but in the on change event, it is updated as the string;

this.setState({ testHighlight: searchBarText });

so, if you modify the above line to:

<HighlighterImplementation testHighlight={this.state.testHighlight.split('')} />

and while initializing state it should be the string will do the trick

Related