Skip to content

Instantly share code, notes, and snippets.

@awinogradov
Created October 11, 2018 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awinogradov/4124abccc571a4ec9ea5f18ea098723a to your computer and use it in GitHub Desktop.
Save awinogradov/4124abccc571a4ec9ea5f18ea098723a to your computer and use it in GitHub Desktop.
conditional-component
import * as React from 'react';
export type Condition<P> = (props: P) => boolean;
export type Body<P> = (Component: React.ComponentType<P>, props: P) => JSX.Element;
type Dictionary<P> = P & {
[key: string]: string;
}
export function matchProps<P>(subset: Partial<P>): (props: P) => boolean {
return (props: P): boolean => Object.keys(subset).every(key => (props as Dictionary<P>)[key] === (subset as Dictionary<P>)[key]);
}
export function withCondition<P>(condition: Condition<P>, cb?: Body<P>) {
return function WithCondition(WrappedComponent: React.ComponentType<P>) {
return function ConditionalComponent(props: P) {
if (condition(props)) {
return cb
? cb(WrappedComponent, props)
: <WrappedComponent {...props} />;
}
return <WrappedComponent {...props} />;
};
};
}
import * as React from 'react';
import { cn } from '@bem-react/classname';
import './Ticket-Point.css';
const cnTicket = cn('Ticket');
export interface ITicketPointProps {
className?: string;
mode: 'origin' | 'destination';
time: string;
title?: string;
date: string;
iata: string;
name: string;
}
export const TicketPoint: React.SFC<ITicketPointProps> = props => (
<div className={cnTicket('Point', { mode: props.mode })}>
<div className={cnTicket('PointTime')}>{props.time}</div>
<div className={cnTicket('PointTitle')}>{props.title}</div>
<div className={cnTicket('PointDate')}>{props.date}</div>
</div>
);
import * as React from 'react';
import { withCondition, matchProps } from './conditional-component';
import { ITicketPointProps } from '../Ticket-Point';
export const TicketPointModeOrigin = withCondition<ITicketPointProps>(
matchProps({ mode: 'origin'}),
(TicketPoint, props) => (
<TicketPoint {...props} title={`${props.iata}, ${props.name}`} />
),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment