How does it work?
SearchBox offers a lightweight and performance focused searchbox UI component to query and display results from your Elasticsearch cluster.
Props
Configure appbase.io environment
The below props are only needed if you're not using the SearchBox
component under SearchBase provider. These props can also be used to override the global environment defined in the SearchBase component.
index
Type | Optional |
---|---|
string |
No |
Refers to an index of the Elasticsearch cluster.
Note:
Multiple indexes can be connected to by specifying comma-separated index names.
url
Type | Optional |
---|---|
string |
No |
URL for the Elasticsearch cluster
credentials
Type | Optional |
---|---|
string |
No |
Basic Auth credentials if required for authentication purposes. It should be a string of the format username:password
. If you are using an appbase.io cluster, you will find credentials under the Security > API credentials
section of the appbase.io dashboard.
appbaseConfig
Type | Optional |
---|---|
Object |
Yes |
allows you to customize the analytics experience when appbase.io is used as a backend. It accepts an object which has the following properties:
- recordAnalytics
Boolean
allows recording search analytics (and click analytics) when set totrue
and appbase.io is used as a backend. Defaults tofalse
. - enableQueryRules
Boolean
Iffalse
, then appbase.io will not apply the query rules on the search requests. Defaults totrue
. - enableSearchRelevancy
Boolean
defaults totrue
. It allows you to configure whether to apply the search relevancy or not. - userId
string
It allows you to define the user id to be used to record the appbase.io analytics. Defaults to the client's IP address. - useCache
Boolean
This property when set allows you to cache the current search query. TheuseCache
property takes precedence irrespective of whether caching is enabled or disabled via the dashboard. - customEvents
Object
It allows you to set the custom events which can be used to build your own analytics on top of appbase.io analytics. Further, these events can be used to filter the analytics stats from the appbase.io dashboard. - enableTelemetry
Boolean
When set tofalse
, disable the telemetry. Defaults totrue
.
To configure the ReactiveSearch API
The following properties can be used to configure the appbase.io ReactiveSearch API:
id
Type | Optional |
---|---|
string |
No |
unique identifier of the component, can be referenced in other components' react
prop.
index
Type | Optional |
---|---|
string |
Yes |
The index prop can be used to explicitly specify an index to query against for this component. It is suitable for use-cases where you want to fetch results from more than one index in a single ReactiveSearch API request. The default value for the index
is set to the index prop defined in the SearchBase component. You can check out the full example here.
<SearchBox
...
index="good-books-clone"
/>
dataField
Type | Optional |
---|---|
string | Array<string | DataField> |
No |
index field(s) to be connected to the component’s UI view. SearchBox accepts an Array
in addition to string
, which is useful for searching across multiple fields with or without field weights.
Field weights allow weighted search for the index fields. A higher number implies a higher relevance weight for the corresponding field in the search results.
You can define the dataField
property as an array of objects of the DataField
type to set the field weights.
The DataField
type has the following shape:
type DataField = {
field: string;
weight: number;
};
queryFormat
Type | Optional |
---|---|
string |
Yes |
Sets the query format, can be or or and. Defaults to or.
or
returns all the results matching any of the search query text's parameters. For example, searching for "bat man" with or will return all the results matching either "bat" or "man".
- On the other hand with and, only results matching both "bat" and "man" will be returned. It returns the results matching all of the search query text's parameters.
react
Type | Optional |
---|---|
Object |
Yes |
react
prop is useful for components whose data view should reactively update when on or more dependent components change their states, e.g. a component to display the results can depend on the search component to filter the results.
- key
string
one ofand
,or
,not
defines the combining clause.- and clause implies that the results will be filtered by matches from all of the associated component states.
- or clause implies that the results will be filtered by matches from at least one of the associated component states.
- not clause implies that the results will be filtered by an inverse match of the associated component states.
- value
string or Array or Object
string
is used for specifying a single component by itsid
.Array
is used for specifying multiple components by theirid
.Object
is used for nesting other key clauses.
An example of a react
clause where all three clauses are used and values are Object
, Array
and string
.
<SearchBox
id="search-component"
dataField={['original_title', 'original_title.search']}
react={{
and: {
or: ['CityComp', 'TopicComp'],
not: 'BlacklistComp',
},
}}
/>
Here, we are specifying that the suggestions should update whenever one of the blacklist items is not present and simultaneously any one of the city or topics matches.
size
Type | Optional |
---|---|
number |
Yes |
Number of suggestions and results to fetch per request.
from
Type | Optional |
---|---|
number |
Yes |
To define from which page to start the results, it is important to implement pagination.
includeFields
Type | Optional |
---|---|
Array<string> |
Yes |
fields to be included in search results.
excludeFields
Type | Optional |
---|---|
Array<string> |
Yes |
fields to be excluded in search results.
sortBy
Type | Optional |
---|---|
string |
Yes |
sort the results by either asc
or desc
order.
aggregationField
Type | Optional |
---|---|
string |
Yes |
One of the most important use-cases this enables is showing DISTINCT
results (useful when you are dealing with sessions, events, and logs type data).
It utilizes composite aggregations
which are newly introduced in ES v6 and offer vast performance benefits over a traditional terms aggregation.
You can read more about it over here.
You can use aggregationData
using onAggregationData
callback or subscriber
.
Note: This prop has been marked as deprecated starting v1.2.0. Please use the
distinctField
prop instead.
<SearchBox
id="search-component"
dataField={['original_title', 'original_title.search']}
aggregationField="original_title.keyword"
onAggregationData={(next, prev) => {}}
/>
aggregationSize
To set the number of buckets to be returned by aggregations.
Note: This is a new feature and only available for appbase versions >= 7.41.0.
highlight
Type | Optional |
---|---|
Boolean |
Yes |
whether highlighting should be enabled in the returned results.
highlightField
Type | Optional |
---|---|
string or Array |
Yes |
when highlighting is enabled, this prop allows specifying the fields which should be returned with the matching highlights. When not specified, it defaults to applying highlights on the field(s) specified in the dataField prop.
customHighlight
Type | Optional |
---|---|
Object |
Yes |
It can be used to set the custom highlight settings. You can read the Elasticsearch
docs for the highlight options at here.
categoryField
Type | Optional |
---|---|
string |
Yes |
Data field whose values are used to provide category specific suggestions.
categoryValue
Type | Optional |
---|---|
string |
Yes |
This is the selected category value. It is used for informing the search result.
nestedField
Type | Optional |
---|---|
string |
Yes |
set the nested
field path that allows an array of objects to be indexed in a way that can be queried independently of each other. Applicable only when dataField's mapping is of nested
type.
fuzziness
Type | Optional |
---|---|
string | number |
Yes |
Set a maximum edit distance on the search parameters, which can be 0, 1, 2, or "AUTO". This is useful for showing the correct results for an incorrect search parameter by taking the fuzziness into account. For example, with a substitution of one character, the fox can become a box. Read more about it in the elastic search docs
enableSynonyms
Type | Optional |
---|---|
Boolean |
Yes |
This property can be used to control (enable/disable) the synonyms behavior for a particular query. Defaults to true
, if set to false
then fields having .synonyms
suffix will not affect the query.
rankFeature
Type | Optional |
---|---|
Object |
Yes |
This property allows you to define the Elasticsearch rank feature query to boost the relevance score of documents based on the rank_feature
fields. Read more about it here.
The rankFeature
object must be in the following shape:
{
"field_name": {
"boost": 1.0,
"function_name": "function_object"
}
}
field_name
It represents thedataField
that has therank_feature
orrank_features
mapping.boost
[optional] A floating point number (shouldn't be negative) that is used to decrease (if the value is between 0 and 1) or increase relevance scores (if the value is greater than 1). Defaults to 1.function_name
To calculate relevance scores based on rank feature fields, the rank_feature query supports the following mathematical functions:function_object
The function object can be used to override the default values for functions.saturation
function supports thepivot
property that must be greater than zero.log
function supports thescaling_factor
propertysigmoid
function supportspivot
andexponent
[must be positive] properties
The following example uses a rank feature field named pagerank
with saturation
function.
{
"id": "search",
"dataField": ["content"],
"value": "2016",
"rankFeature": {
"pagerank": {
"saturation": {
"pivot": 2
}
}
}
}
The following example uses the boost
property to boost the relevance score based on the pagerank
field.
{
"id": "search",
"dataField": ["content"],
"value": "2016",
"rankFeature": {
"pagerank": {
"boost": 2.0
}
}
}
The following example uses all three functions (saturation
, log
and sigmoid
) to boost the relevance scores.
{
"query": [
{
"id": "search",
"dataField": [
"content"
],
"value": "2016",
"rankFeature": {
"pagerank": {
"saturation": {
"pivot": 2
}
},
"url_length": {
"log": {
"scaling_factor": 1
}
},
"topics.sports": {
"sigmoid": {
"pivot": 2,
"exponent": 1
}
}
}
}
]
}
searchOperators
Type | Optional |
---|---|
Boolean |
Yes |
Defaults to false
. If set to true
, then you can use special characters in the search query to enable the advanced search.
Read more about it here.
queryString
Type | Optional |
---|---|
Boolean |
Yes |
Defaults to false
. If set to true
then it allows you to create a complex search that includes wildcard characters, searches across multiple fields, and more. Read more about it here.
clearOnQueryChange
Type | Optional |
---|---|
Boolean |
Yes |
Defaults to true
, i.e. clear the component's input selection when the query of its dependent component changes (which is set via react prop). When set to false
, the component's input selection isn't cleared.
distinctField
Type | Optional |
---|---|
String |
Yes |
This prop returns only the distinct value documents for the specified field. It is equivalent to the DISTINCT
clause in SQL. It internally uses the collapse feature of Elasticsearch. You can read more about it over here.
distinctFieldConfig
Type | Optional |
---|---|
Object |
Yes |
This prop allows specifying additional options to the distinctField
prop. Using the allowed DSL, one can specify how to return K distinct values (default value of K=1), sort them by a specific order, or return a second level of distinct values. distinctFieldConfig
object corresponds to the inner_hits
key's DSL. You can read more about it over here.
<SearchBox
....
distinctField="authors.keyword"
distinctFieldConfig={{
inner_hits: {
name: 'most_recent',
size: 5,
sort: [{ timestamp: 'asc' }],
},
max_concurrent_group_searches: 4,
}}
/>
value
Type | Optional |
---|---|
string |
Yes |
sets the current value of the component. It sets the search query text (on mount and on update). Use this prop in conjunction with the onChange
prop.
onChange
Type | Optional |
---|---|
Function |
Yes |
is a callback function which accepts component's current value as a parameter. It is called when you are using the value
prop and the component's value changes. This prop is used to implement the controlled component behavior.
<SearchBox
value={this.state.text}
onChange={(value, searchComponent, e) => {
// Perform actions after updating the value
this.setState(
{
text: value,
},
() => {
// To fetch suggestions
searchComponent.triggerDefaultQuery();
// To update results
searchComponent.triggerCustomQuery();
},
);
}}
/>
To customize the AutoSuggestions
enablePopularSuggestions
Type | Optional |
---|---|
Boolean |
Yes |
Defaults to false
. When set to true
, popular searches are returned as suggestions as per the popular suggestions config (either defaults, or as set through popularSuggestionsConfig
or via Suggestions settings in the control plane). Read more about it over here.
It can accept the following keys:
- size:
number
Maximum number of popular suggestions to return. Defaults to 5. - minCount:
number
Return only popular suggestions that have been searched at leastminCount
times. There is no default minimum count-based restriction. - minChars:
number
Return only popular suggestions that have minimum characters, as set in this property. There is no default minimum character-based restriction. - showGlobal:
Boolean
Defaults totrue
. When set tofalse
, returns popular suggestions only based on the current user's past searches. - index:
string
Index(es) from which to return the popular suggestions from. Defaults to the entire cluster.
```jsx
Type | Optional |
---|---|
Boolean |
Yes |
Defaults to false
. When set to true
, recent searches are returned as suggestions as per the recent suggestions config (either defaults, or as set through recentSuggestionsConfig
or via Recent Suggestions settings in the control plane)
Note: Please note that this feature only works when
recordAnalytics
is set totrue
inappbaseConfig
.
recentSuggestionsConfig
Type | Optional |
---|---|
Object |
Yes |
Specify additional options for fetching recent suggestions.
It can accept the following keys:
- size:
number
Maximum number of recent suggestions to return. Defaults to 5. - minHits:
number
Return only recent searches that returned at leastminHits
results. There is no default minimum hits-based restriction. - minChars:
number
Return only recent suggestions that have minimum characters, as set in this property. There is no default minimum character-based restriction. - index:
string
Index(es) from which to return the recent suggestions from. Defaults to the entire cluster.
```jsx
enablePredictiveSuggestions
Type | Optional |
---|---|
Boolean |
Yes |
Defaults to false
. When set to true
, it predicts the next relevant words from a field's value based on the search query typed by the user. When set to false (default), the matching document field's value would be displayed.
// pass this prop as true in searchComponent to enable predictive suggestions
enablePredictiveSuggestions: true,
maxPredictedWords
Type | Optional |
---|---|
number |
Yes |
Defaults to 2
. This property allows configuring the maximum number of relevant words that are predicted. Valid values are between [1, 5].
applyStopwords
Type | Optional |
---|---|
Boolean |
Yes |
When set to true, it would not predict a suggestion which starts or ends with a stopword. You can find the list of stopwords used by Appbase at here.
stopwords
Type | Optional |
---|---|
Array[String] |
Yes |
It allows you to define a list of custom stopwords. You can also set it through Index
settings in the control plane.
showDistinctSuggestions
Type | Optional |
---|---|
Boolean |
Yes |
Show 1 suggestion per document. If set to false
multiple suggestions may show up for the same document as
searched value might appear in multiple fields of the same document, this is true only if you have configured multiple fields in dataField
prop. Defaults to true
.
Example if you have showDistinctSuggestions
is set to false
and have following configurations
// Your document:
{
"name": "Warn",
"address": "Washington"
}
// Component:
<SearchBox dataField={['name', 'address']} />
// Search Query:
"wa"
Then there will be 2 suggestions from the same document
as we have the search term present in both the fields
specified in dataField
.
Warn
Washington
urlField
Type | Optional |
---|---|
string |
Yes |
It is the dataField
whose value contains a URL. This is a convenience prop that allows returning the URL value in the suggestion's response.
To customize the SearchBox UI
title
Type | Optional |
---|---|
string|JSX |
Yes |
set the title of the component to be shown in the UI.
loader
Type | Optional |
---|---|
string|JSX |
Yes |
Display an optional loader while fetching the options
placeholder
Type | Optional |
---|---|
string |
Yes |
set placeholder text to be shown in the component's input field. Defaults to "Search".
showIcon
Type | Optional |
---|---|
Boolean |
Yes |
whether to display a search or custom icon in the input box. Defaults to true
.
iconPosition
Type | Optional |
---|---|
string |
Yes |
sets the position of the search icon. Can be set to either left
or right
. Defaults to right
.
icon
Type | Optional |
---|---|
JSX |
Yes |
set a custom search icon instead of the default 🔍
showClear
Type | Optional |
---|---|
Boolean |
Yes |
show a clear text X
icon. Defaults to false
.
clearIcon
Type | Optional |
---|---|
any |
Yes |
sets custom clear icon for the search input box
autosuggest
Type | Optional |
---|---|
Boolean |
Yes |
set whether the autosuggest functionality should be enabled or disabled. Defaults to true
.
strictSelection
Type | Optional |
---|---|
Boolean |
Yes |
defaults to false
. When set to true
, the component will only set its value and fire the query if the value was selected from the suggestion. Otherwise the value will be cleared
on selection. This is only relevant with autosuggest
.
defaultSuggestions
Type | Optional |
---|---|
suggestionsDef |
Yes |
preset search suggestions to be shown on focus when the SearchBox does not have any search query text set. Accepts an array of objects each having a label and value property. The label can contain either String or an HTML element. For an example
<SearchBox
defaultSuggestions={[
{
label: 'Songwriting',
value: 'Songwriting'
},
{
label: 'Musicians',
value: 'Musicians'
}
]}
>
downShiftProps
Type | Optional |
---|---|
Object |
Yes |
are the props to be passed to DownShift
for typeahead configurations
debounce
Type | Optional |
---|---|
wholeNumber |
Yes |
delays executing the query by the specified time in ms while the user is typing. Defaults to 0
, i.e. no debounce. Useful if you want to save on the number of requests sent.
showVoiceSearch
Type | Optional |
---|---|
Boolean |
Yes |
Enable voice search for searchbox
render
Type | Optional |
---|---|
Function |
Yes |
You can render suggestions in a custom layout by using the render
prop.
It accepts an object with these properties:
loading
:Boolean
indicates that the query is still in progress.
error
:Object
An object containing the error info.
suggestions
() => Array<Object>
This method can be used to get the parsed suggestions from the results
. The suggestion
object will have the following shape:
{
label: string;
value: string;
_suggestion_type: String;
source: Object;
}
-
results
Results
It is an object which contains the following details ofsuggestions
query response.data
:Array<Object>
contains the (promoted data + parsed hits)raw
:Object
Response returned by ES query in the raw form.numberOfResults
:number
Total number of results foundtime
:number
Total time taken by request (in ms)hidden
:number
Total number of hidden results foundpromoted
:number
Total number of promoted results foundpromotedData
:Array<Object>
An array of promoted results obtained from the applied query.customData
:Object
An object of custom data obtained from the ReactiveSearch API.
-
rawData
:Object
An object of raw response as-is from elasticsearch query. -
aggregationData
Aggregations
It is an object which contains the following details ofaggregations
query response.data
:Array<Object>
contains the parsed aggregationsraw
:Object
Response returned by EScomposite aggs
query in the raw form.rawData
:Object
An object of raw response as-is from elasticsearch query.afterKey
:Object
If the number of composite buckets is too high (or unknown) to be returned in a single response use theafterKey
parameter to retrieve the next results. This property will only be present forcomposite
aggregations.
-
value
current search input value i.e the search query being used to obtain suggestions. -
query
Object
The last query that has been executed to fetch the suggestions -
micStatus
MicStatusField
Returns the current status of the mic. Can beINACTIVE
,ACTIVE
orDENIED
-
micActive
Boolean
Returnstrue
if mic is active -
micInactive
Boolean
Returnstrue
if mic is inactive -
micDenied
Boolean
Returnstrue
if it doesn't have access to the mic -
micInstance
Object
Returns the current mic instance. Can be used to set mic language and other properties of mic -
id
string
as defined in props -
react
Object
react
as defined in props -
queryFormat
string
as defined in props -
dataField
string | Array<string | DataField>
as defined in props -
categoryField
string
as defined in props -
categoryValue
string
represents the current value of the selected category -
nestedField
string
as defined in props -
from
number
represents the current state of thefrom
value. This property is useful to implement pagination. -
size
number
represents the current state of thesize
of results to be returned by query -
sortBy
string
current state of thesortBy
value -
aggregationField
string
as defined in props -
includeFields
Array<string>
represents the current value ofincludeFields
property -
excludeFields
represents the current value ofexcludeFields
property -
fuzziness
string|number
represents the current value offuzziness
property -
searchOperators
Boolean
as defined in props -
highlight
Boolean
as defined in props -
highlightField
string|Array<string>
as defined in props -
customHighlight
Object
as defined in props -
enableSynonyms
Boolean
as defined in props -
queryString
string
as defined in props -
enablePopularSuggestions
Boolean
as defined in props -
showDistinctSuggestions
Boolean
as defined in props -
defaultQuery
represents the current value ofdefaultQuery
property -
customQuery
represents the current value ofcustomQuery
property -
requestStatus
represents the current state of the request, can have values asINACTIVE
,PENDING
orERROR
. -
appbaseConfig
Object
as defined in props -
queryId
string
to get the query id returned by appbase.io search to track the analytics -
subscribeToStateChanges
function
can be used to subscribe to the changes for the properties. Read more at here. -
unsubscribeToStateChanges
function
can be used to unsubscribe to the changes for the properties. Read more at here. -
recordClick
function
enables recording click analytics of a search request. Please check the usage at here. -
recordConversions
function
enables recording conversions of a search request. Please check the usage at here.
Note:
All of the methods accept
options
as the second parameter which has the following shape:
{
triggerDefaultQuery?: boolean, // defaults to `true`
triggerCustomQuery?: boolean, // defaults to `false`
stateChanges?: boolean // defaults to `true`
};
triggerDefaultQuery
`true` executes the query for a particular component
triggerCustomQuery
`true` executes the query for the dependent components (dependencies defined in the `react` property)
stateChanges
true
invokes the subscribed functions to subscribeToStateChanges
method, i.e trigger the re-render after making changes
handleMicClick
(micOptions: Object, options: Options): Promise<any>
can be used to handle the custom voice search implementationtriggerDefaultQuery
(options): Promise<any>
can be used to trigger thecustomQuery
programmaticallytriggerCustomQuery
(options): Promise<any>
can be used to trigger thedefaultQuery
programmaticallysetDataField
( dataField: string | Array<string | DataField>, options?: Options ) => void
setValue
( value: any, options?: Options ) => void
can be used to set thevalue
property- setCategoryValue
(categoryValue: string, options?: Options) => void
can be used to set thecategoryValue
property. setSize
( size: number, options?: Options ) => void
can be used to set thesize
propertysetFrom
( from: number, options?: Options ) => void
can be used to set thefrom
property. Useful to implement pagination.- setAfter
(after: object, options?: Options) => void
can be used to set the after
property, which is useful while implementing pagination when the type
of the component is term
. The after
key is a a property of aggregationData
.
setFuzziness
( fuzziness: string|number, options?: Options ) => void
can be used to set thefuzziness
property.setIncludeFields
( includeFields: Array<string>, options?: Options ) => void
can be used to set theincludeFields
property.setExcludeFields
( excludeFields: Array<string>, options?: Options ) => void
can be used to set theexcludeFields
property.setSortBy
( sortBy: string, options?: Options ) => void
can be used to set thesortBy
property.setReact
( react: Object, options?: Options ) => void
can be used to set thereact
property.setDefaultQuery
( defaultQuery: function, options?: Options ) => void
can be used to set thedefaultQuery
property.setCustomQuery
( customQuery: function, options?: Options ) => void
can be used to set thecustomQuery
property.
renderError
Type | Optional |
---|---|
Function |
Yes |
can be used to render an error message in case of any error.
<SearchBox
renderError={error => (
<div>
Something went wrong!
<br />
Error details
<br />
{JSON.stringify(error)}
</div>
)}
/>
renderNoSuggestion
Type | Optional |
---|---|
string|JSX |
Yes |
can be used to render a message in case of no list items.
renderMic
Type | Optional |
---|---|
Function |
Yes |
can be used to render the custom mic option
recentSearchesIcon
Type | Optional |
---|---|
JSX |
Yes |
You can use a custom icon in place of the default icon for the recent search items that are shown when enableRecentSearches
prop is set to true. You can also provide styles using the recent-icon
key in the innerClass
prop.
<SearchBox
...
enableRecentSearches
innerClass={{
'recent-search-icon': '...',
}}
recentSearchesIcon={<RecentIcon />}
/>
popularSearchesIcon
Type | Optional |
---|---|
JSX |
Yes |
You can use a custom icon in place of the default icon for the popular searches that are shown when enablePopularSuggestions
prop is set to true. You can also provide styles using the popular-icon
key in the innerClass
prop.
<SearchBox
...
enablePopularSuggestions
innerClass={{
'popular-search-icon': '...'
}}
popularSearchesIcon={<PopularIcon />}
/>
focusShortcuts
Type | Optional |
---|---|
Array<string | number> |
Yes |
A list of keyboard shortcuts that focus the search box. Accepts key names and key codes. Compatible with key combinations separated using '+'. Defaults to ['/']
.
Note
- By default, pressing
'/'
would focus the search box.- The
hotkeys-js
library needs to be installed manually when using combinations infocusShortcuts
prop, eg: 'cmd+b', 'ctrl+q', etc, without which only single key shortcuts would work if passed in the prop, eg: From among ['/', 'b', '#', 'ctrl+r'], only '/', 'b', '#' would work without hotkey-js installation.
autoFocus
Type | Optional |
---|---|
Boolean |
Yes |
When set to true, search box is auto-focused on page load. Defaults to false
.
addonBefore
Type | Optional |
---|---|
string|JSX |
Yes |
The HTML markup displayed before (on the left side of) the searchbox input field. Users can use it to render additional actions/ markup, eg: a custom search icon hiding the default.
<SearchBox
showIcon={false}
addonBefore={
<img
src="https://img.icons8.com/cute-clipart/64/000000/search.png"
height="30px"
/>
}
id="search-component"
...
/>
addonAfter
Type | Optional |
---|---|
string|JSX |
Yes |
The HTML markup displayed after (on the right side of) the searchbox input field. Users can use it to render additional actions/ markup, eg: a custom search icon hiding the default.
<SearchBox
showIcon={false}
addonAfter={
<img
src="https://img.icons8.com/cute-clipart/64/000000/search.png"
height="30px"
/>
}
id="search-component"
...
/>
expandSuggestionsContainer
Type | Optional |
---|---|
Boolean |
Yes |
When set to false the width of suggestions dropdown container is limited to the width of searchbox input field. Defaults to true
.
<SearchBox
expandSuggestionsContainer={false}
addonBefore={
<img ... />
}
addonAfter={
<img ... />
}
id="search-component"
...
/>
enterButton
Type | Optional |
---|---|
boolean |
Yes |
When set to true
, the results would only be updated on press of the button. Defaults to false
. You can also provide styles using the enter-button
key in the innerClass
prop.
<SearchBox
id="search-component"
enterButton={true}
/>
renderEnterButton
Type | Optional |
---|---|
Function |
Yes |
renders a custom jsx markup for the enter button. Use in conjunction with enterButton
prop set to true
.
<SearchBox
id="search-component"
enterButton
renderEnterButton={clickHandler => (
<div
style={{
height: '100%',
display: 'flex',
alignItems: 'stretch',
}}
>
<button style={{ border: '1px solid #c3c3c3' }} onClick={clickHandler}>
🔍 Search
</button>
</div>
)}
/>
Customize style
innerClass
Type | Optional |
---|---|
Object |
Yes |
SearchBox
component supports an innerClass
prop to provide styles to the sub-components of SearchBox
. These are the supported keys:
title
input
list
recent-search-icon
popular-search-icon
enter-button
className
Type | Optional |
---|---|
String |
Yes |
CSS class to be injected on the component container.
style
Type | Optional |
---|---|
Object |
Yes |
CSS styles to be applied to the SearchBox component.
Controlled behavior
defaultValue
Type | Optional |
---|---|
string |
Yes |
set the initial search query text on mount.
value
Type | Optional |
---|---|
string |
Yes |
sets the current value of the component. It sets the search query text (on mount and on update). Use this prop in conjunction with the onChange
prop.
onChange
Type | Optional |
---|---|
Function |
Yes |
is a callback function which accepts component's current value as a parameter. It is called when you are using the value
prop and the component's value changes.
Callbacks for change events
onValueChange
Type | Optional |
---|---|
Function |
Yes |
is a callback function which accepts component's current value as a parameter. It is called every-time the component's value changes. This prop is handy in cases where you want to generate a side-effect on value selection. For example: You want to show a pop-up modal with the valid discount coupon code when a user searches for a product in a SearchBox.
onValueSelected
Type | Optional |
---|---|
Function |
Yes |
A function callback which executes on selecting a value from result set
onError
Type | Optional |
---|---|
Function |
Yes |
gets triggered in case of an error while fetching results
onResults
Type | Optional |
---|---|
Function |
Yes |
can be used to listen for the suggestions changes
onQueryChange
Type | Optional |
---|---|
Function |
Yes |
is a callback function which accepts component's prevQuery and nextQuery as parameters. It is called everytime the component's query changes. This prop is handy in cases where you want to generate a side-effect whenever the component's query would change.
onBlur
Type | Optional |
---|---|
Function |
Yes |
is a callback handler for input blur event
onKeyPress
Type | Optional |
---|---|
Function |
Yes |
is a callback handler for keypress event
onKeyUp
Type | Optional |
---|---|
Function |
Yes |
is a callback handler for keyup event
onFocus
Type | Optional |
---|---|
Function |
Yes |
is a callback handler for input focus event
onKeyDown
Type | Optional |
---|---|
Function |
Yes |
is a callback handler for keydown event
onAggregationData
Type | Optional |
---|---|
Function |
Yes |
can be used to listen for the aggregationData
property changes
- data:
Array<Object>
contains the parsed aggregations - raw:
Object
Response returned by ES composite aggs query in the raw form. - rawData:
Object
An object of raw response as-is from elasticsearch query. - afterKey:
Object
If the number of composite buckets is too high (or unknown) to be returned in a single response use the afterKey parameter to retrieve the next
To customize the query execution
- headers
Object
set custom headers to be sent with each server request as key/value pairs. For example:
<SearchBox id="search-component" dataField={['original_title', 'original_title.search']} />
- transformRequest
(requestOptions: Object) => Promise<Object>
Enables transformation of network request before execution. This function will give you the request object as the param and expect an updated request in return, for execution.
For example, we will add thecredentials
property in the request usingtransformRequest
.
<SearchBox
id="search-component"
dataField={['original_title', 'original_title.search']}
transformRequest={request =>
Promise.resolve({
...request,
credentials: include,
})
}
/>
- transformResponse
(response: any) => Promise<any>
Enables transformation of search network response before rendering them. It is an asynchronous function which will accept an Elasticsearch response object as param and is expected to return an updated response as the return value.
For example:
<SearchBox
id="search-component"
dataField={['original_title', 'original_title.search']}
transformResponse={async elasticsearchResponse => {
const ids = elasticsearchResponse.hits.hits.map(item => item._id);
const extraInformation = await getExtraInformation(ids);
const hits = elasticsearchResponse.hits.hits.map(item => {
const extraInformationItem = extraInformation.find(
otherItem => otherItem._id === item._id,
);
return {
...item,
...extraInformationItem,
};
});
return {
...elasticsearchResponse,
hits: {
...elasticsearchResponse.hits,
hits,
},
};
}}
/>
Note
transformResponse
function is expected to return data in the following structure.
{
// Elasticsearch hits response
hits: {
hits: [...],
total: 100
},
// Elasticsearch aggregations response
aggregations: {
}
took: 1
}
-
defaultQuery:
(component: SearchComponent) => Object
is a callback function that takes SearchComponent instance as parameter and returns the data query to be applied to the suggestions, as defined in Elasticsearch Query DSL, which doesn't get leaked to other components. In simple words,defaultQuery
is used with data-driven components to impact their own data.For example, set the
timeout
to1s
for suggestion query.
<SearchBox
id="search-component"
dataField={["original_title", "original_title.search"]}
defaultQuery={() => ({
"timeout": "1s"
})}
/>
-
customQuery:
(component: SearchComponent) => Object
takes SearchComponent instance as parameter and returns the query to be applied to the dependent components byreact
prop, as defined in Elasticsearch Query DSL.For example, the following example has two components
search-component
(to render the suggestions) andresult-component
(to render the results). Theresult-component
depends on thesearch-component
to update the results based on the selected suggestion. Thesearch-component
has thecustomQuery
prop defined that will not affect the query for suggestions(that is howcustomQuery
is different fromdefaultQuery
) but it'll affect the query forresult-component
because of thereact
dependency onsearch-component
.
<SearchBase
index="gitxplore-app"
url="https://@arc-cluster-appbase-demo-6pjy6z.searchbase.io"
credentials="a03a1cb71321:75b6603d-9456-4a5a-af6b-a487b309eb61"
/>
<SearchBox
id="search-component"
dataField={["original_title", "original_title.search"]}
customQuery={
() => ({
timeout: '1s',
query: {
match_phrase_prefix: {
fieldName: {
query: 'hello world',
max_expansions: 10,
},
},
},
})
}
/>
<SearchComponent
id="result-component"
dataField="original_title"
react={{
and: ['search-component']
}}
/>
Miscellaneous
getMicInstance
Type | Optional |
---|---|
Function |
Yes |
You can pass a callback function to get the instance of SpeechRecognition
object, which can be used to override the default configurations for voice search.
- beforeValueChange
Function
is a callback function which accepts component's future value as a parameter and returns a promise. It is called every-time before a component's value changes. The promise, if and when resolved, triggers the execution of the component's query and if rejected, kills the query execution. This method can act as a gatekeeper for query execution, since it only executes the query after the provided promise has been resolved. For example:
<SearchBox
id="search-component"
dataField={['original_title', 'original_title.search']}
beforeValueChange={function(value) {
// called before the value is set
// returns a promise
return new Promise((resolve, reject) => {
// update state or component props
resolve();
// or reject()
});
}}
/>
URLParams
Type | Optional |
---|---|
Boolean |
Yes |
enable creating a URL query string param based on the search query text value. This is useful for sharing URLs with the component state. Defaults to false
.
- subscribeTo
Array<string>
lets you subscribe to various Searchbox properties to render UI (or to create a side-effect) based on changes to the properties.
These are the properties that can be subscribed to:
results
aggregationData
requestStatus
error
value
query
micStatus
dataField
size
from
fuzziness
includeFields
excludeFields
sortBy
react
defaultQuery
customQuery