SearchBox
editSearchBox
editInput element which accepts search terms and triggers a new search query.
Example
editimport { SearchBox } from "@elastic/react-search-ui"; ... <SearchBox />
Configuring search queries
editThe input from SearchBox
will be used to trigger a new search query. That query can be further customized
in the SearchProvider
configuration, using the searchQuery
property. See the Search Query Configuration guide for more information.
Example of passing custom props to text input element
edit<SearchBox inputProps={{ placeholder: "custom placeholder" }} />
Example using autocomplete results
edit"Results" are search results. The default behavior for autocomplete results is to link the user directly to a result when selected, which is why a "titleField" and "urlField" are required for the default view.
<SearchBox autocompleteResults={{ titleField: "title", urlField: "nps_link" }} />
Example using autocomplete suggestions
edit"Suggestions" are different than "results". Suggestions are suggested queries. Unlike an autocomplete result, a suggestion does not go straight to a result page when selected. It acts as a regular search query and refreshes the result set.
<SearchBox autocompleteSuggestions={true} />
Example using autocomplete suggestions and autocomplete results
editThe default view will show both results and suggestions, divided into sections. Section titles can be added to help distinguish between the two.
<SearchBox autocompleteResults={{ sectionTitle: "Suggested Results", titleField: "title", urlField: "nps_link" }} autocompleteSuggestions={{ sectionTitle: "Suggested Queries" }} />
Example retrieving suggestions from another index
editSupported only by the Elasticsearch-connector.
A different index can be used for the suggestions. Some examples:
- Popular queries index from analytics
- Brands index from product data
- Categories index from product data
Below we are using the popular_queries
index and performing a prefix match search on the query.suggest
field. One thing to note, make sure the api-key has access to the index.
Autocomplete Configuration
editautocompleteQuery: { suggestions: { types: { popularQueries: { search_fields: { "query.suggest": {} // fields used to query }, result_fields: { query: { // fields used for display raw: {} } }, index: "popular_queries", queryType: "results" } }, size: 4 } }
Component Configuration
edit<SearchBox autocompleteSuggestions={{ popularQueries: { queryType: "results", displayField: "query" // specify which field used to display the suggestion }, } }} />
You also have the option to customise the view
of the autocomplete to show more fields.
Configuring autocomplete queries
editAutocomplete queries can be customized in the SearchProvider
configuration, using the autocompleteQuery
property.
See the Autocomplete Query Configuration for more information.
<SearchProvider config={{ ... autocompleteQuery: { // Customize the query for autocompleteResults results: { result_fields: { // Add snippet highlighting title: { snippet: { size: 100, fallback: true } }, nps_link: { raw: {} } } }, // Customize the query for autocompleteSuggestions suggestions: { types: { // Limit query to only suggest based on "title" field documents: { fields: ["title"] } }, // Limit the number of suggestions returned from the server size: 4 } } }} > <SearchBox autocompleteResults={{ sectionTitle: "Suggested Results", titleField: "title", urlField: "nps_link" }} autocompleteSuggestions={{ sectionTitle: "Suggested Queries", }} /> </SearchProvider>
Example using multiple types of autocomplete suggestions
edit"Suggestions" can be generated via multiple methods. They can be derived from common terms and phrases inside of documents, or be "popular" queries generated from actual search queries made by users. This will differ depending on the particular Search API you are using.
Note: Elastic App Search currently only supports type "documents", and Elastic Site Search and Workplace Search do not support suggestions. This is purely illustrative in case a Connector is used that does support multiple types.
<SearchProvider config={{ ... autocompleteQuery: { suggestions: { types: { documents: { }, // FYI, this is not a supported suggestion type in any current connector, it's an example only popular_queries: { } } } } }} > <SearchBox autocompleteSuggestions={{ // Types used here need to match types requested from the server documents: { sectionTitle: "Suggested Queries", }, popular_queries: { sectionTitle: "Popular Queries" } }} /> </SearchProvider>
Example using autocomplete in a site header
editThis is an example from a Gatsby site, which overrides "submit" to navigate a user to the search page for suggestions, and maintaining the default behavior when selecting a result.
<SearchBox autocompleteResults={{ titleField: "title", urlField: "nps_link" }} autocompleteSuggestions={true} onSubmit={(searchTerm) => { navigate("/search?q=" + searchTerm); }} onSelectAutocomplete={(selection, {}, defaultOnSelectAutocomplete) => { if (selection.suggestion) { navigate("/search?q=" + selection.suggestion); } else { defaultOnSelectAutocomplete(selection); } }} />
Properties
editName | Description |
---|---|
className |
|
shouldClearFilters |
Should existing filters be cleared when a new search is performed? |
inputProps |
Props for underlying input element. I.e., |
searchAsYouType |
Executes a new search query with every key stroke. You can fine tune the number of queries made by adjusting the |
debounceLength |
When using |
autocompleteResults |
Configure and autocomplete search results. Boolean option is primarily available for implementing custom views. |
autocompleteSuggestions |
Configure and autocomplete query suggestions. Boolean option is primarily available for implementing custom views. Configuration may or may not be keyed by "Suggestion Type", as APIs for suggestions may support may than 1 type of suggestion. If it is not keyed by Suggestion Type, then the configuration will be applied to the first type available. |
autocompleteMinimumCharacters |
Minimum number of characters before autocompleting. |
onSelectAutocomplete |
Allows overriding behavior when selected, to avoid creating an entirely new view. In addition to the current |
onSubmit |
Allows overriding behavior when submitted. Receives the search term from the search box. |
autocompleteView |
Used to override only the autocomplete dropdown. See Autocomplete view customization below. |
inputView |
Used to override only the input box. See Input view customization below. |
view |
Used to override the default view for this Component. See Full view customization below. |
* |
Any other property passed will be passed through and available to use in a Custom View |
AutocompleteResultsOptions
editName | Description |
---|---|
linkTarget |
Used to open links in a new tab. |
sectionTitle |
Title to show in section within dropdown. |
shouldTrackClickThrough |
Only applies to Results, not Suggestions. |
clickThroughTags |
Tags to send to analytics API when tracking clickthrough. |
titleField |
Field within a Result to use as the "title". |
urlField |
Field within a Result to use for linking. |
AutocompleteSuggestionsOptions
editName | Description |
---|---|
sectionTitle |
Title to show in section within dropdown |
View customization
editA complete guide to view customization can be found in the Customization: Component views and HTML section.
Full view customization
editYou can customize the entire view using the view
prop. This is useful to use an entirely different
autocomplete library (we use downshift). A SearchBox component at its simplest could look like the following:
<SearchBox view={({ value, onChange, onSubmit }) => ( <form onSubmit={onSubmit}> <input type="text" value={value} onChange={(e) => onChange(e.target.value)} /> <input type="submit" value="Search" /> </form> )} />
The full list of props available to this view are as follows:
Name | Description |
---|---|
className |
Passed through from main component. |
inputView |
Component to use for text input. When rendering, pass all props documented below in the Input view customization section. Note that this can be challenging to do since some of the required props are generated by Downshift. It’s generally advised not to try to use this property directly when creating a custom view. |
isFocused |
Type: |
onChange |
Type: |
onSubmit |
Type: |
value |
Type: |
inputProps |
An object containing props that should be spread over the input box element. You’ll need to do this in order to have the |
autocompleteView |
Component to use for Autocomplete. When rendering, pass all props documented below in the Autocomplete view customization section. Note that this can be challenging to do since some of the required props are generated by Downshift. It’s generally advised not to try to use this property directly when creating a custom view. |
completeSuggestion |
Type: |
notifyAutocompleteSelected |
Type: |
autocompletedSuggestionsCount |
Type: |
autocompleteSuggestions |
Type: |
autocompletedSuggestions |
Type: |
autocompletedResults |
Type: |
autocompleteResults |
Type: |
onSelectAutocomplete |
Type: |
allAutocompletedItemsCount |
Type: |
useAutocomplete |
Type: |
See SearchBox.tsx for an example.
Input view customization
editFor making small customizations, like simply hiding the search button, or rearranging DOM structure, full customization is often overkill.
You can also just customize the input section of the search box using the inputView
prop.
<SearchBox inputView={({ getAutocomplete, getInputProps, getButtonProps }) => ( <> <div className="sui-search-box__wrapper"> <input {...getInputProps({ placeholder: "I am a custom placeholder" })} /> {getAutocomplete()} </div> <input {...getButtonProps({ "data-custom-attr": "some value" })} /> </> )} />
Note that getInputProps
and getButtonProps
are
prop getters.
They are meant return a props object to spread over their corresponding UI elements. This lets you arrange
elements however you’d like in the DOM. It also lets you pass additional properties. You should pass properties
through these functions, rather directly on elements, in order to not override base values. For instance,
adding a className
through these functions will assure that the className is only appended, not overriding the base class values.
getAutocomplete
is used to determine where the autocomplete dropdown will be shown.
The full list of props available to this view are as follows:
Name | Description |
---|---|
getAutocomplete |
Type: |
getButtonProps |
Type: |
getInputProps |
Type: |
See SearchInput.tsx for an example.
Autocomplete view customization
editIn addition to the inputView
customization, you can also make targed customization to the autocomplete view using the autocompleteView
prop.
For example:
<SearchBox autocompleteView={({ autocompletedResults, getItemProps }) => ( <div className="sui-search-box__autocomplete-container"> {autocompletedResults.map((result, i) => ( <div {...getItemProps({ key: result.id.raw, item: result })} > Result {i}: {result.title.snippet} </div> ))} </div> )} />
The full list of props available to this view are as follows:
Name | Description |
---|---|
allAutocompletedItemsCount |
Type: |
autocompleteResults |
Type: |
autocompletedResults |
Type: |
autocompletedSuggestions |
Type: |
autocompletedSuggestionsCount |
Type: |
autocompleteSuggestions |
Type: |
onSelectAutocomplete |
Type: |
getItemProps |
Type: |
getMenuProps |
Type: |
See Autocomplete.tsx for an example.