Code With Wolf


Flexsearch Tutorial with React

Flexsearch Tutorial with React JS

Flexsearch is an efficient and highly customizable search library built with JavaScript that can be used to easily add searching into a web application.

You can read more about it in their docs here, and how their scoring algorithm works and how to customize and further enhance your web application's search functionality. There are tons of useful options.

I'm still exploring what various options exist within their search index setup, but I thought one of the more confusing parts was setting up a search index initially.

Let's try it out here. I'll be doing this in a react component because that is what my web app uses, but it would work the same way with any javascript framework (node, vue, etc).

import React, { useEffect, useState } from "react";
import { Index } from "flexsearch";

export default () => {

//  First we need data to search. We will just hard code some stuff for now.

  const data = {
    1: { id: 1, title: "React" },
    2: { id: 2, title: "React.js" },
    3: { id: 3, title: "ReactJS" },
    4: { id: 4, title: "Node" },
    5: { id: 5, title: "Node.js" },
    6: { id: 6, title: "NodeJS" }
  };

    // This will create a new search index. Here we are using all of the default options, but the docs show other choices that can be used. 

  const [index, setIndex] = useState(new Index({}));

    //  Create state variables for query and results.

  const [query, setQuery] = useState("");
  const [results, setResults] = useState([]);

    //  When the component first loads, we need to iterate through data values and add each to the search index. 

  useEffect(() => {
    Object.values(data).forEach((item) => {
      setIndex(index.add(item.id, item.title));
    });
  }, []);

    //  When the query from the search input changes, we want to update the query state and thus the results to display. 

  useEffect(() => {
    setResults(index.search(query));
  }, [query]);

  return (
    <div>
      <input value={query} onChange={(e) => setQuery(e.target.value)} />
      <ul>
        {results.map((result) => (
          <li class="title" key={result}>
            {data[result].title}
          </li>
        ))}
      </ul>
    </div>
  );
};

The results will be the IDs for the items that match the query, so to display the title in the li items, we display data[result].title.

This is a very basic example to get you started. On the react side, we could debounce the input. On the flexsearch side we can add caching, change the scoring algorithm to include partial word search, and much more. Check out their docs to learn more.



© 2022 Code With Wolf