Skip to main content

Simple Form

Creating simple forms with the @rexlabs/form library is fairly straight-forward. All you need is four components:

  • ReactForms
  • Form
  • Field
  • An Input component that implements the FieldInput interface

ReactForms is a context provider and stores all of the state related to the form. It also provides several functions that allow the user to interact with the form state. A good rule of thumb is to memoize all props passed to ReactForms since if the context provider rerenders, so does basically everything else in the form.

Form is a wrapper around the html <form /> element to automatically add an onSubmit handler. It is also responsible for rendering global and non-blocking errors above the form. By default the Form component will only render the first global error it finds, this behaviour can be changed by passing a custom Error component to the Form.

The Field component consumed the context from it's parent ReactForms and facillitates interaction between the user and the Input. It is also responsible for rendering a consistent UI for all of the fields.

Input components are any component that implement the Input interface. They are used to gather user input to be processed by the form.

import React, { useCallback } from 'react';

import { ReactForms, Form, Field } from '@rexlabs/form';
import { EmailInput } from '@rexlabs/text-input';
import { PasswordInput } from '@rexlabs/password-input';

export function LoginFormComponent() {
const handleSubmit = useCallback((values, { setServerError }) => {
return fetch('/login', {
method: 'POST',
body: JSON.stringify(values),
headers: {
'Content-Type': 'application/json'
}
})
.then((result) => result.json())
.catch(setServerError);
}, []);

return (
<ReactForms handleSubmit={handleSubmit}>
{() => {
return (
<Form>
<Field name='email' label='Email' Input={EmailInput} />
<Field name='password' label='Password' Input={PasswordInput} />
<button type='submit'>Login</button>
</Form>
);
}}
</ReactForms>
);
}