Behind The Scenes: Edition 2 - Adding Search To A Static Site Part 2
This is part two of how we added search to our site. Check part-1
to see the Jekyll portion and how we’re outputting the documents that we want to index.
To actually performed the search we built out a small react component to listen
for search input, take the term, search using lunrjs and display the results
under the search bar. We wrote the
component in Typescript which is something we would hardly ever leave home without 😝.
Let’s first see it in action:
Let’s break it down how we implemented the above:
So first we to create our react element by using our identifier class .js-search:
Next we need to pull the documents provided by jekyll and put onto the window (as covered by part 1)
We pull in the documents and then we push them into lunrjs so that it can index
the documents so we can later search based on that index:
Now that we have the const idx available we can use that in our component
to seach if a user types something in our search bar. We have an interface
for our search state to help us keep track of the state of our search component:
We then create our component with some a listener on the document. One thing that
we often talk about is keyboard shortcuts on a website. One implementation on our
search that we have is the ability to initiate a search by simply pressing the “/”
key. So if you land on our website and press “/” it will immediately put our
search bar in focus and you can start typing right away to search. Check the code
with some additional comments:
Next we assign some listeners for the document, for the search input
Let’s see when those listeners are triggered by checking out how our component is
As you see we have a few listeners attached to our search input (key down, change, focus, and blur).
On the search submit we have a listener on click of the search submit button. In
the SearchContainer styled component we iterate over the results and if it is a social
post we show a certain icon and another if it is not. In the ResultItem
we have a link so that on click the user can be taken to the post that they searched for.
Let’s see how we actually get the results and prepare the results array:
And that’s it! This component does a lot and makes for (we hope) a pleasant
search experience 😌. You can check out the entire component in our