Skip to content

TextField - replace withFieldState HOC with useFieldState hook #925

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 6, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions generatedTypes/incubator/TextField/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import { ValidationMessagePosition } from './types';
import { InputProps } from './Input';
import { ValidationMessageProps } from './ValidationMessage';
import { LabelProps } from './Label';
import { FieldStateProps } from './withFieldState';
import { Validator } from './useFieldState';
import { FloatingPlaceholderProps } from './FloatingPlaceholder';
import { CharCounterProps } from './CharCounter';
interface TextFieldProps extends InputProps, LabelProps, FloatingPlaceholderProps, FieldStateProps, ValidationMessageProps, Omit<CharCounterProps, 'maxLength'> {
interface TextFieldProps extends InputProps, LabelProps, FloatingPlaceholderProps, ValidationMessageProps, Omit<CharCounterProps, 'maxLength'> {
/**
* Pass to render a leading button/icon
*/
Expand All @@ -25,6 +25,22 @@ interface TextFieldProps extends InputProps, LabelProps, FloatingPlaceholderProp
* Custom style for the floating placeholder
*/
floatingPlaceholderStyle?: TextStyle;
/**
* A single or multiple validator. Can be a string (required, email) or custom function.
*/
validate?: Validator | Validator[];
/**
* Should validate when the TextField mounts
*/
validateOnStart?: boolean;
/**
* Should validate when the TextField value changes
*/
validateOnChange?: boolean;
/**
* Should validate when losing focus of TextField
*/
validateOnBlur?: boolean;
/**
* The position of the validation message (top/bottom)
*/
Expand Down
23 changes: 23 additions & 0 deletions generatedTypes/incubator/TextField/useFieldState.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { TextInputProps } from 'react-native';
import validators from './validators';
export declare type Validator = Function | keyof typeof validators;
export interface FieldStateProps extends TextInputProps {
validateOnStart?: boolean;
validateOnChange?: boolean;
validateOnBlur?: boolean;
/**
* A single or multiple validator. Can be a string (required, email) or custom function.
*/
validate?: Validator | Validator[];
}
export default function useFieldState({ validate, validateOnBlur, validateOnChange, validateOnStart, ...props }: FieldStateProps): {
onFocus: (...args: any) => void;
onBlur: (...args: any) => void;
onChangeText: (text: any) => void;
fieldState: {
value: string | undefined;
hasValue: boolean;
isValid: boolean;
isFocused: boolean;
};
};
36 changes: 26 additions & 10 deletions src/incubator/TextField/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React, {useMemo} from 'react';
import {ViewStyle, TextStyle} from 'react-native';
import _ from 'lodash';
import {
asBaseComponent,
forwardRef,
Expand All @@ -14,10 +13,7 @@ import AccessoryButton from './AccessoryButton';
import ValidationMessage, {ValidationMessageProps} from './ValidationMessage';
import Label, {LabelProps} from './Label';
import FieldContext from './FieldContext';
import withFieldState, {
FieldStateInjectedProps,
FieldStateProps
} from './withFieldState';
import useFieldState, {Validator/* , FieldStateProps */} from './useFieldState';
import FloatingPlaceholder, {
FloatingPlaceholderProps
} from './FloatingPlaceholder';
Expand All @@ -27,7 +23,8 @@ interface TextFieldProps
extends InputProps,
LabelProps,
FloatingPlaceholderProps,
FieldStateProps,
// We're declaring these props explicitly here for react-docgen
// FieldStateProps,
ValidationMessageProps,
Omit<CharCounterProps, 'maxLength'> {
/**
Expand All @@ -46,6 +43,22 @@ interface TextFieldProps
* Custom style for the floating placeholder
*/
floatingPlaceholderStyle?: TextStyle;
/**
* A single or multiple validator. Can be a string (required, email) or custom function.
*/
validate?: Validator | Validator[];
/**
* Should validate when the TextField mounts
*/
validateOnStart?: boolean;
/**
* Should validate when the TextField value changes
*/
validateOnChange?: boolean;
/**
* Should validate when losing focus of TextField
*/
validateOnBlur?: boolean;
/**
* The position of the validation message (top/bottom)
*/
Expand All @@ -62,7 +75,7 @@ interface TextFieldProps

interface InternalTextFieldProps
extends TextFieldProps,
Omit<FieldStateInjectedProps, keyof InputProps>,
// Omit<FieldStateInjectedProps, keyof InputProps>,
ForwardRefInjectedProps {}

interface StaticMembers {
Expand Down Expand Up @@ -100,13 +113,13 @@ const TextField = (
// Char Counter
showCharCounter,
charCounterStyle,
// Field State
fieldState,
// Input
placeholder,
...props
}: InternalTextFieldProps
) => {
const {onFocus, onBlur, onChangeText, fieldState} = useFieldState(props);

const context = useMemo(() => {
return {...fieldState, disabled: props.editable === false};
}, [fieldState, props.editable]);
Expand Down Expand Up @@ -141,6 +154,9 @@ const TextField = (
)}
<Input
{...props}
onFocus={onFocus}
onBlur={onBlur}
onChangeText={onChangeText}
placeholder={floatingPlaceholder ? undefined : placeholder}
hint={hint}
/>
Expand Down Expand Up @@ -173,5 +189,5 @@ TextField.displayName = 'Incubator.TextField';
TextField.validationMessagePositions = ValidationMessagePosition;

export default asBaseComponent<TextFieldProps, StaticMembers>(
forwardRef(withFieldState(TextField as any))
forwardRef(TextField as any)
);
90 changes: 90 additions & 0 deletions src/incubator/TextField/useFieldState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import {useCallback, useState, useEffect, useMemo} from 'react';
import {TextInputProps} from 'react-native';
import _ from 'lodash';
import validators from './validators';

export type Validator = Function | keyof typeof validators;

export interface FieldStateProps extends TextInputProps {
validateOnStart?: boolean;
validateOnChange?: boolean;
validateOnBlur?: boolean;
/**
* A single or multiple validator. Can be a string (required, email) or custom function.
*/
validate?: Validator | Validator[];
}

export default function useFieldState({
validate,
validateOnBlur,
validateOnChange,
validateOnStart,
...props
}: FieldStateProps) {
const [value, setValue] = useState(props.value);
const [isFocused, setIsFocused] = useState(false);
const [isValid, setIsValid] = useState(true);

useEffect(() => {
if (validateOnStart) {
validateField();
}
}, []);

const validateField = useCallback(
(valueToValidate = value) => {
let _isValid = true;
if (_.isFunction(validate)) {
_isValid = validate(valueToValidate);
} else if (_.isString(validate)) {
_isValid = _.invoke(validators, validate, valueToValidate);
}

setIsValid(_isValid);
},
[value, validate]
);

const onFocus = useCallback(
(...args: any) => {
setIsFocused(true);
_.invoke(props, 'onFocus', ...args);
},
[props.onFocus]
);

const onBlur = useCallback(
(...args: any) => {
setIsFocused(false);
_.invoke(props, 'onBlur', ...args);
if (validateOnBlur) {
validateField();
}
},
[props.onBlur, validateOnBlur, validateField]
);

const onChangeText = useCallback(
(text) => {
setValue(text);
_.invoke(props, 'onChangeText', text);

if (validateOnChange) {
validateField(text);
}
},
[props.onChangeText, validateOnChange, validateField]
);

const fieldState = useMemo(() => {
return {value, hasValue: !_.isEmpty(value), isValid, isFocused};
}, [value, isFocused, isValid]);

return {
onFocus,
onBlur,
onChangeText,
fieldState
};
}