Created
April 2, 2020 21:06
-
-
Save walidvb/466341261f0f9c8db931d237e1af43c5 to your computer and use it in GitHub Desktop.
Resettable Searchable Dropdown – via Context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this is an attempt at not adding redux just yet | |
import React, { createContext, useContext, useCallback, useEffect, useState } from 'react' | |
const Context = createContext({}) | |
const Provider = React.memo(({ value, children }) => <Context.Provider value={value}> | |
{children} | |
</Context.Provider>) | |
export const SearchableProvider = (props) => { | |
const [value, setValue] = useState(initialState) | |
const reset = () => setValue('') | |
return <Provider {...props} value={{value, reset}}/> | |
} | |
export const useSearchableContext = () => useContext(Context) | |
export default SearchableDropdown = ({ onSelect }) => { | |
return <Context.Consumer> | |
({ value }) => (<SearchableInput value={value} />) | |
</Context.Consumer> | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import { SearchableDropdown } from './SearchableContext' | |
export default UserManagement = ({ onSelect }) => { | |
const { reset } = useSearchableContext() | |
const onSearch = async (query) => { | |
const list = await fetchUsers(query) | |
reset() | |
} | |
return <SearchableDropdown onSelect={(user) => onSelect(user, { reset })}/>) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import { SearchableProvider } from './SearchableContext'; | |
export default UserManagement = ({ onSelect }) => { | |
const onSelect = (user, { reset }) => { | |
handleUserSelected(user) | |
reset() | |
} | |
return <SearchableProvider> | |
<SearchableDropdown onSelect={onSelect} /> | |
</SearchableProvider> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment