Skip to main content

Custom Inputs

Input componenents take user input and sends it up to a state manager to be used by other components / methods. To be able work seamlessly with the @rexlabs/form libraries Field component, these components need to implement a specific interface because the Field component sends props down to the given Input component.

Required props​

interface ChangeEvent {
target: {
value?: any;
// This will be used for any input of `type` `number`
valueAsNumber?: number;
checked?: boolean;
files?: File[];
};
}

interface RequiredInputProps {
value: any;
onChange: (e: ChangeEvent<ElementType>) => void;
onBlur: (e: ChangeEvent<ElementType>) => void;
}

Without these three props the input won't interact with the form correctly.

value​

Control prop that should be used as the source of truth for the value of the input. This state is updated every time the onChange handler is run.

onChange​

Callback that should be run whenever the value should be changed. This only affects the local value and will not update the form state when the function is run.

onBlur​

Callback that should be run whenever the form state value should be changed. This will re-render the entire form so should only be used when all user interaction has finished.

Optional props​

The Field component also passes a couple of optional props down to the Input which can be used to enhance the functionality of each input. These props are non-standard and are only guaranteed to work with @rexlabs/form

interface OptionalInputProps {
meta?: {
touched?: boolean;
isDirty?: boolean;
isValidating?: boolean;
isValid?: boolean;
error?: FormError;
};
actions?: {
setValue: (value: any) => void;
setTouched: (touched: boolean) => void;
setError: (error: string | FormError) => void;
validate: (value: any) => void;
};
}

meta​

This prop contains all of the meta information about the field, the most common use-case for this is to style the input differently if the field is not valid, or if there is an error present.

actions​

Various actions that modify the state of the form for this specific field.

Example​

import React from 'react';

export function TextInput({ value, onChange, onBlur, ...props }) {
return (
<input
type='text'
value={value}
// The default `onChange` and `onBlur` handle text inputs fine
// so no customisation needs to be done here
onChange={handleChange}
onBlur={handleBlur}
/>
);
}