Skip to content

Instantly share code, notes, and snippets.

@arminyahya
Last active February 24, 2020 17:24
Show Gist options
  • Save arminyahya/ec238e5bf32422079a5c5b6463b0375a to your computer and use it in GitHub Desktop.
Save arminyahya/ec238e5bf32422079a5c5b6463b0375a to your computer and use it in GitHub Desktop.
This hoc wrap is used to add a float lable to form input
import * as React from 'react';
import { Omit, removeKeys } from '../utilities';
export interface Props {
label: string | React.Component;
value?: any;
error?: string;
onChange: (newValue?: any) => void;
isRequired?: boolean;
focused?: boolean;
placeHolder?: string;
}
export interface States {
isFocused: boolean;
}
export default function FloatMaker<P extends Props>(Component: React.ComponentType<P>) {
return class FloatItem extends React.Component<P, States> {
state = { isFocused: false };
setFocus = () => {
this.setState({ isFocused: true });
}
setBlur = () => {
this.setState({ isFocused: false });
}
checkFloatClass = (value: any) => {
const isFocused = this.state.isFocused;
if (Array.isArray(value) && value.length === 0 && !isFocused) {
return '';
} else if (isFocused || !!value) {
return ' js-float';
} else {
return '';
}
}
render() {
const { label, value, error, isRequired, placeHolder } = this.props;
const { isFocused } = this.state;
const ComponentProps = {
onFocus: this.setFocus,
onBlur: this.setBlur,
value: value,
...removeKeys(this.props, ['error', 'label'])
};
return (
<div className={'y-floating-input' + this.checkFloatClass(value) + (error ? ' js-error' : '')}>
{label && <label>{label} {isRequired && <span className="required-sign" />} </label>}
<Component {...ComponentProps as any} placeHolder={isFocused ? placeHolder : ''} />
</div>
);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment