Skip to content

Instantly share code, notes, and snippets.

@xcollantes
Last active July 5, 2023 04:55
Show Gist options
  • Select an option

  • Save xcollantes/8a32c29e1e7aa9166df1b02d99e11ffa to your computer and use it in GitHub Desktop.

Select an option

Save xcollantes/8a32c29e1e7aa9166df1b02d99e11ffa to your computer and use it in GitHub Desktop.
React Context template in TypeScript
/**
* React context for selecting category filters.
*
* Usage:
* ```
* <SelectFilterTagContextProvider>
* ...
* </SelectFilterTagContextProvider>
* ```
*/
import {
useState,
Dispatch,
SetStateAction,
createContext,
useContext,
ReactNode,
Context,
} from "react"
import { CardContentType, defaultData } from "../testData"
export interface SelectFilterTagContextType {
selected: CardContentType[]
setSelected: Dispatch<SetStateAction<CardContentType[]>>
}
const SelectedFilterTagContext = createContext<SelectFilterTagContextType>({
selected: [],
setSelected: (selected: CardContentType[]) => {},
})
export function useSelectedFilterTagContext(): SelectFilterTagContextType {
return useContext(SelectedFilterTagContext)
}
interface ProviderPropType {
children: ReactNode
}
export function SelectFilterTagContextProvider({ children }: ProviderPropType) {
const [selected, setSelected] = useState<CardContentType[]>(defaultData)
return (
<SelectedFilterTagContext.Provider value={{ selected, setSelected }}>
{children}
</SelectedFilterTagContext.Provider>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment