Skip to content

Commit

Permalink
Add AutocompleteContext to Autocomplete component exports (#2153)
Browse files Browse the repository at this point in the history
  • Loading branch information
willglas committed Jun 28, 2022
1 parent 72266b9 commit ce45de3
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/dry-stingrays-drum.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@primer/react': patch
---

Add AutocompleteContext to Autocomplete component exports
58 changes: 58 additions & 0 deletions docs/content/Autocomplete.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,64 @@ const MultiSelectAddNewItem = () => {
render(<MultiSelectAddNewItem />)
```

#### Rendered with `Autocomplete.Context`

The `Autocomplete.Context` can be used to control the menu open/closed state and customize certain `Autocomplete` behaviors

```javascript live noinline
export function AutocompleteWithContext() {
return (
<Autocomplete>
<AutocompleteWithContextInternal />
</Autocomplete>
)
}

export function AutocompleteWithContextInternal() {
const autocompleteContext = useContext(Autocomplete.Context)
if (autocompleteContext === null) {
throw new Error('AutocompleteContext returned null values')
}

const {setShowMenu, showMenu} = autocompleteContext
const inputRef = useRef < HTMLInputElement > null
const [filterText, setFilterText] = useState('')

useEffect(() => {
if (!showMenu) {
// keep the menu open
setShowMenu(true)
}
}, [showMenu, setShowMenu])

const change = event => setFilterText?.(event.target.value)

return (
<Autocomplete.Context.Provider
value={{...autocompleteContext, autocompleteSuggestion: '', setAutocompleteSuggestion: () => false}}
>
<Autocomplete.Input ref={inputRef} value={filterText} onChange={change} />
<Autocomplete.Overlay>
<Autocomplete.Menu
items={[
{text: 'main', id: 0},
{text: 'autocomplete-tests', id: 1},
{text: 'a11y-improvements', id: 2},
{text: 'button-bug-fixes', id: 3},
{text: 'radio-input-component', id: 4},
{text: 'release-1.0.0', id: 5},
{text: 'text-input-implementation', id: 6},
{text: 'visual-design-tweaks', id: 7}
]}
selectedItemIds={[]}
selectionVariant="single"
/>
</Autocomplete.Overlay>
</Autocomplete.Context.Provider>
)
}
```
## Props
### Autocomplete.Input
Expand Down
1 change: 1 addition & 0 deletions src/Autocomplete/Autocomplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ export type {AutocompleteInputProps} from './AutocompleteInput'
export type {AutocompleteMenuProps} from './AutocompleteMenu'
export type {AutocompleteOverlayProps} from './AutocompleteOverlay'
export default Object.assign(Autocomplete, {
Context: AutocompleteContext,
Input: AutocompleteInput,
Menu: AutocompleteMenu,
Overlay: AutocompleteOverlay
Expand Down

0 comments on commit ce45de3

Please sign in to comment.