formik#useField TypeScript Examples
The following examples show how to use
formik#useField.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: text-field.component.tsx From master-frontend-lemoncode with MIT License | 7 votes |
TextFieldComponent: React.FunctionComponent<TextFieldProps> = props => {
const [field, meta] = useField(props.name);
const textFieldProps = Boolean(field) ? field : props;
const hasError = Boolean(meta && meta.touched && meta.error);
return (
<MuiTextField
{...props}
name={textFieldProps.name}
onChange={textFieldProps.onChange}
onBlur={textFieldProps.onBlur}
value={textFieldProps.value}
error={hasError}
helperText={hasError ? meta.error : ''}
fullWidth={true}
margin="normal"
/>
);
}
Example #2
Source File: NameField.tsx From amplication with Apache License 2.0 | 6 votes |
NameField = ({ capitalized, ...rest }: Props) => {
const [regexp, pattern, helpText] = capitalized
? [CAPITALIZED_NAME_REGEX, CAPITALIZED_NAME_PATTERN, CAPITALIZED_HELP_TEXT]
: [NAME_REGEX, NAME_PATTERN, HELP_TEXT];
// @ts-ignore
const [field, meta] = useField<string>({
...rest,
validate: (value) => (value.match(regexp) ? undefined : helpText),
});
const [showMessage, setShowMessage] = useState<boolean>(false);
const [debouncedHideMessage] = useDebouncedCallback(() => {
setShowMessage(false);
}, SHOW_MESSAGE_DURATION);
useEffect(() => {
if (meta.error) {
setShowMessage(true);
} else {
debouncedHideMessage();
}
}, [meta.error, setShowMessage, debouncedHideMessage]);
return (
<div className={CLASS_NAME}>
<TextInput
{...field}
{...rest}
label="Name"
autoComplete="off"
minLength={1}
pattern={pattern}
/>
{showMessage && (
<div className={`${CLASS_NAME}__tooltip`}>{helpText}</div>
)}
</div>
);
}
Example #3
Source File: InputField.tsx From lireddit with MIT License | 6 votes |
InputField: React.FC<InputFieldProps> = ({
label,
textarea,
size: _,
...props
}) => {
let InputOrTextarea = Input;
if (textarea) {
InputOrTextarea = Textarea;
}
const [field, { error }] = useField(props);
return (
<FormControl isInvalid={!!error}>
<FormLabel htmlFor={field.name}>{label}</FormLabel>
<InputOrTextarea {...field} {...props} id={field.name} />
{error ? <FormErrorMessage>{error}</FormErrorMessage> : null}
</FormControl>
);
}
Example #4
Source File: DatePickerField.tsx From vsinder with Apache License 2.0 | 6 votes |
DatePickerField: React.FC<TextFieldProps> = ({ name, label }) => {
const [open, setOpen] = React.useState(false);
const [field, meta, { setValue }] = useField({ name });
return (
<View>
<MyButton secondary onPress={() => setOpen(true)}>
{label}
</MyButton>
<DateTimePickerModal
date={field.value}
isVisible={open}
mode="date"
onConfirm={(dt) => {
setValue(dt);
setOpen(false);
}}
onCancel={() => setOpen(false)}
/>
{meta.error ? (
<ErrorText style={{ marginTop: 4 }}>{meta.error}</ErrorText>
) : null}
</View>
);
}
Example #5
Source File: FileInput.tsx From frontegg-react with MIT License | 6 votes |
FFileInput = forwardRef<HTMLInputElement, FileInputProps & { name: string }>(
({ validation, ...props }, forwardRef) => {
const { onChange } = props;
const [{ name }, {}, { setValue, setError }] = useField(props.name);
const handlerOnChange = useCallback(
async (e: ChangeEvent<HTMLInputElement>) => {
e.persist();
const selectedFile = e.target.files?.[0];
if (selectedFile) {
const errorMessage = (await validation?.(selectedFile)) ?? null;
if (errorMessage) {
setError(errorMessage);
return;
}
const content = await toBase64(selectedFile);
setValue(content);
} else {
setValue('');
}
onChange && onChange(e);
},
[onChange, setValue, setError, name]
);
return (
<span style={{ display: 'none' }}>
<FileInput {...props} ref={forwardRef} type='file' onChange={handlerOnChange} />
</span>
);
}
)
Example #6
Source File: FormInput.tsx From gear-js with GNU General Public License v3.0 | 6 votes |
FormInput = (props: Props) => {
const { name, label, className, ...other } = props;
const [field, meta] = useField(name);
const showError = meta.error && meta.touched;
return (
<div className={styles.item}>
<Input {...other} {...field} label={label} className={clsx(styles.field, className)} />
{showError && <div className={styles.error}>{meta.error}</div>}
</div>
);
}
Example #7
Source File: checkbox-control.tsx From formik-chakra-ui with MIT License | 6 votes |
CheckboxControl: FC<CheckboxControlProps> = React.forwardRef(
(props: CheckboxControlProps, ref: React.ForwardedRef<HTMLInputElement>) => {
const { name, label, children, ...rest } = props;
const [field, { error, touched }] = useField(name);
let isChecked;
if (field.value instanceof Array) {
isChecked = field.value.includes(props.value) ?? false;
}
return (
<Checkbox
{...field}
isInvalid={!!error && touched}
isChecked={isChecked}
ref={ref}
{...rest}
>
{label}
{children}
</Checkbox>
);
}
)
Example #8
Source File: dob.component.tsx From openmrs-esm-patient-registration with MIT License | 6 votes |
DobField: React.FC = () => {
const { t } = useTranslation();
const [field, meta] = useField('birthdate');
const { setFieldValue } = React.useContext(PatientRegistrationContext);
const { format, placeHolder, dateFormat } = generateFormatting(['d', 'm', 'Y'], '/');
const onDateChange = ([birthdate]) => {
setFieldValue('birthdate', birthdate);
};
// TODO: remove custom styling soon.
return (
<div style={{ marginBottom: '1rem' }}>
<h4 className={styles.productiveHeading02Light}>{t('dobLabelText', 'Birth')}</h4>
<DatePicker dateFormat={dateFormat} datePickerType="single" light onChange={onDateChange}>
<DatePickerInput
id="birthdate"
placeholder={placeHolder}
labelText={t('dateOfBirthLabelText', 'Date of Birth')}
invalid={!!(meta.touched && meta.error)}
invalidText={meta.error}
{...field}
value={format(field.value)}
/>
</DatePicker>
</div>
);
}
Example #9
Source File: UploadSSH.tsx From assisted-ui-lib with Apache License 2.0 | 6 votes |
UploadSSH: React.FC = () => {
const [{ name, value }, , { setValue }] = useField('sshPublicKey');
return (
<UploadField
label={
<>
{'SSH public key'}
<PopoverIcon
variant="plain"
bodyContent="Provide an SSH key to receive debugging information during installation"
/>
</>
}
name={name}
helperText={<SshPublicKeyHelperText />}
idPostfix="discovery"
onBlur={() => value && setValue(trimSshPublicKey(value))}
dropzoneProps={{
accept: '.pub',
maxSize: 2048,
onDropRejected:
({ setError }) =>
() =>
setError('File not supported.'),
}}
transformValue={trimSshPublicKey}
/>
);
}
Example #10
Source File: CheckboxField.tsx From querybook with Apache License 2.0 | 6 votes |
CheckboxField: React.FC<ICheckboxFieldProps> = ({
name,
...checkboxProps
}) => {
const [_, meta, helpers] = useField(name);
return (
<Checkbox
{...checkboxProps}
value={checkboxProps.value ?? meta.value}
onChange={
checkboxProps.onChange ??
((value) => {
helpers.setValue(value);
helpers.setTouched(true);
})
}
/>
);
}
Example #11
Source File: CampaignTypeSelect.tsx From frontend with MIT License | 6 votes |
export default function CampaignTypeSelect({ name = 'campaignTypeId' }) {
const { t } = useTranslation()
const { data } = useCampaignTypesList()
const [field, meta] = useField(name)
const helperText = meta.touched ? translateError(meta.error as TranslatableField, t) : ''
return (
<FormControl
fullWidth
size="small"
variant="outlined"
error={Boolean(meta.error) && Boolean(meta.touched)}>
<InputLabel>{t('campaigns:campaign.type')}</InputLabel>
<Select fullWidth defaultValue="" label={t('campaigns:campaign.type')} {...field}>
<MenuItem value="" disabled>
{t('campaigns:campaign.type')}
</MenuItem>
{data?.map((campaignType, index) => (
<MenuItem key={index} value={campaignType.id}>
{campaignType.name}
</MenuItem>
))}
</Select>
{helperText && <FormHelperText error>{helperText}</FormHelperText>}
</FormControl>
)
}
Example #12
Source File: SelectRepeatable.tsx From slice-machine with Apache License 2.0 | 6 votes |
SelectRepeatable: React.FC = () => {
const [field, , helpers] = useField<boolean>("repeatable");
return (
<Box mb={2}>
<FlexCard selected={field.value} onClick={() => helpers.setValue(true)}>
<Radio checked={field.value} />
<Box
sx={{
marginLeft: 2,
}}
>
Repeatable type
<Box as="p" sx={{ fontSize: "12px", color: "textClear", mt: 1 }}>
Best for multiple instances like blog posts, authors, products...
</Box>
</Box>
</FlexCard>
<FlexCard selected={!field.value} onClick={() => helpers.setValue(false)}>
<Radio checked={!field.value} />
<Box
sx={{
marginLeft: 2,
}}
>
Single type
<Box as="p" sx={{ fontSize: "12px", color: "textClear", mt: 1 }}>
Best for a unique page, like the homepage or privacy policy page...
</Box>
</Box>
</FlexCard>
</Box>
);
}
Example #13
Source File: Checkbox.tsx From rcvr-app with GNU Affero General Public License v3.0 | 6 votes |
Checkbox: React.FC<CheckboxProps> = ({
label,
hint,
hintEnabled,
...rest
}) => {
const [field, meta] = useField({ ...rest, type: 'checkbox' })
const showError = Boolean(meta.touched && meta.error)
return (
<div>
<CheckboxContainer htmlFor={field.name}>
<div css={{ position: 'relative' }}>
<FakeCheckbox />
<CheckboxCircle
initial={{ scale: 0 }}
animate={{ scale: field.checked ? 1 : 0 }}
/>
{field.checked && <Check />}
</div>
<Text variant="label">{label}</Text>
</CheckboxContainer>
<input
id={field.name}
type="checkbox"
{...field}
{...rest}
css={{ display: 'none' }}
/>
{field.checked && hintEnabled && (
<HintText variant="fineprint">{hintEnabled}</HintText>
)}
{hint && !(field.checked && hintEnabled) && (
<HintText variant="fineprint">{hint}</HintText>
)}
{showError && <ErrorText variant="fineprint">{meta.error}</ErrorText>}
</div>
)
}
Example #14
Source File: FormInput.tsx From mayoor with MIT License | 6 votes |
FormInput: React.FC<Props> = ({ icon, label, name, withLabel, ...rest }) => {
const [{ value, onChange }, { touched, error }] = useField(name);
const errorMessage = touched && error;
const status = errorMessage ? 'error' : '';
const getValue = () => {
if (typeof value === 'string') {
return value;
}
if (typeof value === 'number') {
return value;
}
return '';
};
return (
<StyledFormItem validateStatus={status} help={errorMessage}>
<>
{withLabel && <StyledLabel>{label}</StyledLabel>}
<Input
prefix={icon && icon}
placeholder={label}
name={name}
onChange={onChange}
value={getValue()}
data-test-id={`form-item-${name}`}
{...rest}
/>
</>
</StyledFormItem>
);
}
Example #15
Source File: FileField.tsx From netify with BSD 2-Clause "Simplified" License | 6 votes |
FileField = memo<FileFieldProps>(function FileField({className, name}) {
const [{value, onBlur}, , {setValue}] = useField<File>(name);
const onChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files![0];
if (file) {
setValue(file);
}
},
[setValue],
);
return (
<label className={cn(styles.root, className)}>
<input className={styles.input} name={name} type='file' onChange={onChange} onBlur={onBlur} />
{value ? (
<>
<p className={styles.value}>{value.name}</p>
<p className={styles.note}>Body replacing will also rewrites "Content-Type" header</p>
</>
) : (
<p className={styles.title}>Click to choice a file or drag-n-drop it here</p>
)}
<div className={styles.filler} />
</label>
);
})
Example #16
Source File: select.component.tsx From master-frontend-lemoncode with MIT License | 5 votes |
SelectComponent: React.FunctionComponent<Props> = props => {
const {
name,
items,
label,
error,
onChange,
onBlur,
className,
...otherProps
} = props;
const [field, meta] = Boolean(name) ? useField(name) : [];
const hasError = error || Boolean(meta && meta.touched && meta.error);
const helperText = Boolean(field) ? meta?.error : props.helperText;
const labelId = `${name}-label`;
const value = props.value !== undefined ? props.value : field?.value;
return (
<FormControl
className={className}
error={hasError}
fullWidth={true}
margin="normal"
>
<InputLabel htmlFor={name} id={labelId}>
{label}
</InputLabel>
<Select
{...otherProps}
classes={{
select: classes.select,
}}
id={name}
labelId={labelId}
name={name}
onChange={onChange || field?.onChange}
onBlur={onBlur || field?.onBlur}
value={value}
>
{items.map(item => (
<MenuItem key={item.id} value={item.id}>
{item.name}
</MenuItem>
))}
</Select>
{hasError && <FormHelperText>{helperText}</FormHelperText>}
</FormControl>
);
}