If the text prop is supplied and a matching item is found, onSelect is automatically fired

This commit is contained in:
Tom Southall
2022-05-19 15:41:43 +01:00
parent 28ac24be57
commit 9282c4b7ef
5 changed files with 17 additions and 3 deletions

View File

@@ -1,5 +1,8 @@
# Changelog
### 2.2.0 (19 May 2022)
- If the text prop is supplied and a matching item is found, onSelect is automatically fired
### 2.1.1 (14 May 2022)
- Changing styles prop now triggers a re-render

View File

@@ -575,6 +575,7 @@ in order to exit the focused state of the search box.
- Type: `string`
- Default: `undefined`
- Text appearing in the search box when first rendered
- Will cause `onSelect` to fire automatically if there is a matching result
#### `typeahead`
- Type: `string`

View File

@@ -1,6 +1,6 @@
{
"name": "turnstone",
"version": "2.1.1",
"version": "2.2.0",
"description": "React customisable autocomplete component with typeahead and grouped results from multiple APIs.",
"author": "Tom Southall",
"keywords": [

View File

@@ -1,4 +1,4 @@
import React, { useState, useRef, useContext, useImperativeHandle } from 'react'
import React, { useState, useRef, useContext, useImperativeHandle, useEffect } from 'react'
import { StateContext } from '../context/state'
import Listbox from './listbox'
import Errorbox from './errorbox'
@@ -53,6 +53,7 @@ const Container = React.forwardRef((props, ref) => {
placeholder,
styles,
tabIndex,
text,
typeahead,
Cancel,
Clear
@@ -68,6 +69,7 @@ const Container = React.forwardRef((props, ref) => {
const [debouncedQuery] = useDebounce(state.query, debounceWait)
const [hasFocus, setHasFocus] = useState(false)
const [blockBlurHandler, setBlockBlurHandler] = useState(false)
const [autoSelect, setAutoSelect] = useState(!!text)
// DOM references
const queryInput = useRef(null)
@@ -112,6 +114,14 @@ const Container = React.forwardRef((props, ref) => {
// Store retrieved data in global state as state.items
useItemsState(swrResult.data)
// Autoselect matching value if we have initial text passed in a prop
useEffect(() => {
if(autoSelect && swrResult.data && swrResult.data[0]?.text === text) {
dispatch(setSelected(swrResult.data[0]))
setAutoSelect(false)
}
}, [autoSelect, swrResult.data, text, dispatch])
// Store retrieved error if there is one
useItemsError(swrResult.error)

View File

@@ -1,6 +1,6 @@
import React, { createContext, useReducer, useEffect } from 'react'
import reducer from '../reducers/reducer'
import {setQuery} from '../actions/actions'
import { setQuery } from '../actions/actions'
import undef from '../utils/undef'
const StateContext = createContext()