Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Created August 29, 2019 19:00
Show Gist options
  • Select an option

  • Save OliverJAsh/bebfe1c5690d2e79317103c2b6c4bb9e to your computer and use it in GitHub Desktop.

Select an option

Save OliverJAsh/bebfe1c5690d2e79317103c2b6c4bb9e to your computer and use it in GitHub Desktop.
import memoizeOne from 'memoize-one';
import React, { Component, ComponentType } from 'react';
import { context } from 'react-progressive-enhancement';
import { unionize } from 'unionize';
import { getDisplayName } from 'HOCs/helpers';
import { ObjectOmit } from 'shared/helpers/typescript';
export const RenderType = unionize({
Unenhanced: {},
Enhanced: {},
});
export type RenderType = typeof RenderType._Union;
export type RenderTypeProp = { renderType: RenderType };
const createRenderTypeFromIsEnhanced = (isEnhanced: boolean) =>
isEnhanced ? RenderType.Enhanced() : RenderType.Unenhanced();
const { Consumer } = context;
export const withRenderType = <ComposedProps extends RenderTypeProp>(
ComposedComponent: ComponentType<ComposedProps>,
) => {
type ComposedPropsWithoutRenderTypeProp = ObjectOmit<ComposedProps, RenderTypeProp>;
type Props = ComposedPropsWithoutRenderTypeProp;
const displayName = `WithRenderType(${getDisplayName(ComposedComponent)})`;
class WithRenderType extends Component<Props> {
static displayName = displayName;
// memoized instances to avoid wasted re-renders
createRenderTypeFromIsEnhancedMemoized = memoizeOne(createRenderTypeFromIsEnhanced);
render() {
return (
<Consumer>
{({ isEnhanced }) => {
const renderType = this.createRenderTypeFromIsEnhancedMemoized(isEnhanced);
return (
<ComposedComponent
{
// Cast is workaround for https://github.com/microsoft/TypeScript/issues/28884
...({
renderType,
...this.props,
} as ComposedProps)
}
/>
);
}}
</Consumer>
);
}
}
return WithRenderType;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment