1

I want to use lunr js in an react app to search strings but I don't know how to set up a lunr index. in the documentation it says The Lunr index. This can be an instance of a Lunr index or one that has been exported via JSON.stringify. but I don't know how this is done.

import React, { useState } from 'react'
import { useLunr } from 'react-lunr'
import { Formik, Form, Field } from 'formik'

const index = /* a lunr index */
const store = {
  1: { id: 1, title: 'Document 1' },
  2: { id: 2, title: 'Document 2' },
  3: { id: 3, title: 'Document 3' },
}

const SearchBar = () => {
  const [query, setQuery] = useState(null)
  const results = useLunr(query, index, store)

  return (
    <Formik
      initialValues={{ query: '' }}
      onSubmit={(values, { setSubmitting }) => {
        setQuery(values.query)
        setSubmitting(false)
      }}
    >
      <Form>
        <Field name="query" />
      </Form>
      <h1>Results</h1>
      <ul>
        {results.map(result => (
          <li key={result.id}>{result.title}</li>
        ))}
      </ul>
    </Formik>
  )
}
vuvu
  • 4,886
  • 12
  • 50
  • 73

1 Answers1

4

Looking at the lunr docs a lunr index can be created like so:

import lunr from "lunr";

const index = lunr(function() {
  this.field("title");
  this.field("body");

  this.add({
    title: "Twelfth-Night",
    body: "If music be the food of love, play on: Give me excess of it…",
    author: "William Shakespeare",
    id: "1"
  });
});

The useLunr hook can then take index and use it for searching.

Here's a sandbox that puts all this together!

Hope this helps!

Sam Gomena
  • 1,450
  • 11
  • 21