Last active
July 5, 2023 04:55
-
-
Save xcollantes/8a32c29e1e7aa9166df1b02d99e11ffa to your computer and use it in GitHub Desktop.
React Context template in TypeScript
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
| /** | |
| * 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