Created
August 29, 2019 11:48
-
-
Save xamedow/d4a45e122a90ed47a3a7d96c947d598b to your computer and use it in GitHub Desktop.
This file contains 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 React from 'react'; | |
import PropTypes from 'prop-types'; | |
import { Field } from 'react-final-form'; | |
import { useSpring, animated } from 'react-spring'; | |
interface IProps extends React.HTMLProps<HTMLElement> { | |
when: string; | |
equal?: string | boolean; | |
isIn?: {}; | |
cb?: any; | |
} | |
const Inner = ({ | |
value, | |
equal, | |
cb, | |
isIn, | |
children | |
}: { | |
value: any; | |
equal?: string | boolean; | |
isIn?: {}; | |
cb?: any; | |
children: React.ReactNode; | |
}) => { | |
const plainValue = value.id || value; | |
const contentStatus = plainValue === equal || (isIn && plainValue in isIn) || cb(value); | |
const contentProps = useSpring({ | |
opacity: contentStatus ? 1 : 0, | |
}); | |
if (!contentStatus) return null; | |
return <animated.div style={contentProps}>{children}</animated.div>; | |
}; | |
const Condition = ({ | |
when, | |
equal, | |
isIn = {}, | |
cb = () => {}, | |
children | |
}: IProps) => { | |
return ( | |
<Field name={when} subscription={{ value: true }}>{/* | |
// @ts-ignore */} | |
{({ input: { value } }) => <Inner value={value} isIn={isIn} cb={cb} equal={equal}>{children}</Inner>} | |
</Field> | |
); | |
}; | |
Condition.propTypes = { | |
children: PropTypes.node, | |
when: PropTypes.string.isRequired, | |
equal: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]) | |
}; | |
Condition.defaultProps = {}; | |
export default Condition; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment