justask.dev

Community powered answers to your dev questions

Searchbar for MDX files

posted: 2019 December 9th

category: gatsby

Edit this post on GitHub.

Back

Used in this website, add a search bar to your site to help the user filter your posts or whatever. Influenced by aboutmonica.com/blog/create-gatsby-blog-search-tutorial This example uses Emotion and Theme-Ui for styling.

First we create our search bar hook to handle the logic

1import React from "react";
2
3export const useSearchBar = data => {
4 const allAnswers = data.allMdx.nodes;
5 const emptyQuery = "";
6 const [searchQuery, setSearchQuery] = React.useState({
7 filteredData: [],
8 query: emptyQuery
9 });
10
11 const handleSearchQuery = e => {
12 const query = e.target.value;
13
14 const answers = data.allMdx.nodes || [];
15
16 const filteredData = answers.filter(answer => {
17 const { title } = answer.frontmatter;
18 return title.toLowerCase().includes(query.toLowerCase());
19 });
20
21 setSearchQuery({ filteredData, query });
22 };
23
24 const { filteredData, query } = searchQuery;
25 const hasSearchResult = filteredData && query !== emptyQuery;
26 const answers = hasSearchResult ? filteredData : allAnswers;
27
28 return { answers, handleSearchQuery };
29};

Then we create our search bar which is just a styled input

1/** @jsx jsx */
2import { jsx } from "theme-ui";
3import styled from "@emotion/styled";
4
5const SearchBarContainer = styled.div`
6 display: flex;
7 justify-content: center;
8 align-items: center;
9 margin: 1em auto;
10`;
11
12const Input = styled.input`
13 padding: 0.4em;
14`;
15
16const SearchBar = ({handleSearchQuery}) => {
17 return (
18 <SearchBarContainer>
19 <Input
20 sx={{
21 color: "greyBlack",
22 fontFamily: "body"
23 }}
24 type="text"
25 id="my-id"
26 placeholder="Type to filter.."
27 onChange={handleSearchQuery}
28 />
29 </SearchBarContainer>
30 );
31};
32
33export default SearchBar;

Then we can inport it and use it:

1const { answers, handleSearchQuery } = useSearchBar(data);
2
3 <SearchBar handleSearchQuery={handleSearchQuery} />

Author: Rich Haines