Skip to content

Instantly share code, notes, and snippets.

@xamedow
Created August 29, 2019 11:48
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 xamedow/d4a45e122a90ed47a3a7d96c947d598b to your computer and use it in GitHub Desktop.
Save xamedow/d4a45e122a90ed47a3a7d96c947d598b to your computer and use it in GitHub Desktop.
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