Last active
February 9, 2021 08:21
-
-
Save ronaldruzicka/67969bd2dd2c0004837bcce4345380d2 to your computer and use it in GitHub Desktop.
Example of simple React context in Typescript
This file contains 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 { createContext, useContext, useState } from 'react'; | |
type Props = { | |
children: React.ReactNode | React.ReactNode[]; | |
}; | |
type Context = { | |
isExpanded: boolean; | |
toggleItem?: () => void; | |
}; | |
const AccordionContext = createContext<Context>({ | |
isExpanded: false, | |
toggleItem: undefined, | |
}); | |
const AccordionProvider = ({ children }: Props) => { | |
const [isExpanded, setIsExpanded] = useState<boolean>(false); | |
const toggleItem = () => setIsExpanded((isExpanded) => !isExpanded); | |
return ( | |
<AccordionContext.Provider value={{ isExpanded, toggleItem }}> | |
{children} | |
</AccordionContext.Provider> | |
); | |
}; | |
const useAccordion = () => { | |
const context = useContext(AccordionContext); | |
if (typeof context === 'undefined') { | |
throw new Error('useAccordion must be used within a AccordionProvider'); | |
} | |
return context; | |
}; | |
export { AccordionProvider, useAccordion }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment