Skip to content

Instantly share code, notes, and snippets.

@bouiboui
Last active January 27, 2020 09:27
Show Gist options
  • Save bouiboui/dc65e8a4fa244421db4a47751a54fbf6 to your computer and use it in GitHub Desktop.
Save bouiboui/dc65e8a4fa244421db4a47751a54fbf6 to your computer and use it in GitHub Desktop.
React + Typescript Context Provider with children autocompletion
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