Created
October 11, 2018 11:45
-
-
Save awinogradov/4124abccc571a4ec9ea5f18ea098723a to your computer and use it in GitHub Desktop.
conditional-component
This file contains hidden or 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 * 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} />; | |
}; | |
}; | |
} |
This file contains hidden or 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 * 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> | |
); |
This file contains hidden or 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 * 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