Last active
January 27, 2020 09:27
-
-
Save bouiboui/dc65e8a4fa244421db4a47751a54fbf6 to your computer and use it in GitHub Desktop.
React + Typescript Context Provider with children autocompletion
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 React, { ReactElement, ReactNode, useState } from 'react' | |
export interface IFlagContext { | |
userEmail: string | null | |
sendEmail: boolean | |
changeUserEmail: (email: string) => void | |
} | |
const FlagContext = React.createContext<IFlagContext | null>(null) | |
interface IFlagContextChildren { | |
children: (a: IFlagContext) => ReactNode | |
} | |
const FlagContextProvider = ({ children }: IFlagContextChildren): ReactElement<IFlagContextChildren> => { | |
const [userEmail, changeUserEmail] = useState<string | null>(null) | |
const flagContextHandler = { | |
sendEmail: false, | |
userEmail, | |
changeUserEmail | |
} | |
return ( | |
<FlagContext.Provider value={flagContextHandler}> | |
{children(flagContextHandler)} | |
</FlagContext.Provider> | |
) | |
} | |
const App: React.FunctionComponent = () => { | |
return ( | |
<FlagContextProvider> | |
{({ sendEmail }) => sendEmail && <div>hello</div>} | |
</FlagContextProvider> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment