Skip to content

Instantly share code, notes, and snippets.

View thehappybug's full-sized avatar
🧙‍♂️

Mehdi Raza Jaffery thehappybug

🧙‍♂️
  • APIMATIC
  • Pakistan
View GitHub Profile
// This function takes a component...
export function withAppContext(Component) {
// ...and returns another component...
return function ComponentBoundWithAppContext(props) {
// ... and renders the wrapped component with the current context!
// Notice that we pass through any additional props as well
return (
<AppContextConsumer>
{appContext => <Component {...props} appContext={appContext} />}
</AppContextConsumer>
import * as React from "react";
import { AppContextInterface, withAppContext } from "./AppContext";
const PostInfoComp = ({ appContext }: { appContext?: AppContextInterface }) =>
appContext && (
<div>
Name: {appContext.name} <br />
Author: {appContext.author} <br />
Url: {appContext.url}
</div>
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export function withAppContext<
P extends { appContext?: AppContextInterface },
R = Omit<P, 'appContext'>
>(
Component: React.ComponentClass<P> | React.StatelessComponent<P>
): React.SFC<R> {
return function BoundComponent(props: R) {
return (
<AppContextConsumer>
{appContext => ...}
</AppContextConsumer>
import * as React from 'react';
import { AppContextConsumer } from './AppContext';
export const PostInfo = () => (
<AppContextConsumer>
{appContext => appContext && (
<div>
Name: {appContext.name},
Author: {appContext.author},
Url: {appContext.url}
import * as React from 'react';
import { AppContextInterface, AppContextProvider } from './AppContext';
const sampleAppContext: AppContextInterface = {
name: 'Using React Context in a Typescript App',
author: 'thehappybug',
url: 'http://www.example.com'
};
export const App = () => (
import * as React from 'react';
export interface AppContextInterface {
name: string,
author: string,
url: string
}
const ctxt = React.createContext<AppContextInterface | null>(null);
import * as React from 'react';
interface AppContextInterface {
name: string,
author: string,
url: string
}
const {Provider, Consumer} = React.createContext<AppContextInterface | null>(null);
import * as React from 'react';
interface AppContextInterface {
name: string,
author: string,
url: string
}
const {Provider, Consumer} = React.createContext<AppContextInterface>();
npm update react react-dom @types/react @types/react-dom