Skip to content
Gravity Logo / Docs Gravity home
Browse documentation
Documentation/Gravity Web

Form

You will never experience the pain of coding another HTML form again. The Form component is a self-validating form that accepts an object for inputs. It supports various input types, validation, and can handle file uploads and Stripe payments.

Usage

import { Form } from 'components/lib';

function MyComponent({ ...props }){

  return (
    <Form 
      inputs={{
        name: {
          type: 'text',
          label: 'Name',
          required: true,
        },
        email: {
          type: 'email',
          label: 'Email',
          required: true,
        },
      }}
      url='/api/user'
      method='PATCH'
      buttonText='Save'
      callback={(res) => console.log(res)}
    />
  );
}

Props

PropDescriptionRequiredValue
buttonTextsubmit button textoptionalstring
callbackfunction executed on successful submitoptionalfunction
cancelcancel callback (also shows a cancel button)optionalfunction
classNamecustom stylingoptionalSCSS or Tailwind
destructiveset submit button color to redoptionalboolean
inputsinputs objectrequiredobject (see below)
methodHTTP request typeoptionalstring
onChangecallback function executed on input changeoptionalfunction
redirecturl to redirect to after a successful submitoptionalstring
submitOnChangesubmit the form on each input changeoptionalboolean
urlurl to post the form tooptionalstring

Inputs Object

When constructing a form object, each outer key represents an input name and is associated with an object containing various input properties.

formData = {
 name: {
  label: 'Your name',
  type: 'text',
  required: true,
  placeholder: 'Jon Smith',
  errorMessage: 'Please enter your name',
 }
}

Input Types

The following input types are available.

  • card (creditcard input)
  • checkbox
  • date
  • email
  • file
  • hidden
  • number
  • password
  • phone
  • radio
  • select
  • switch
  • text
  • textarea
  • url
  • otp (one-time password)

Input Props

Props are passed to the input by the form. A full list of props for the inputs can be found below.

PropDescriptionRequiredValue
aria-describedbyid of the element that describes the inputoptionalstring
aria-invaliddetermines if the input is validrequiredboolean
classNamecustom styleoptionalSCSS or Tailwind style
defaultValuedefault valueoptionalstring
disableddisable the inputoptionalboolean
idhtml id for the inputoptionalstring
nameinput namerequiredstring
onChangecallback function executed on changerequiredfunction
placeholderplaceholder textoptionalstring
requireddetermines if a value is requiredoptionalboolean
valuecurrent valueoptionalstring
minminimum valueoptionalinteger
minLengthminimum lengthoptionalinteger
maxmaximum valueoptionalinteger
maxLengthmaximum lengthoptionalinteger
optionsarray of options for a radio, checkbox, or selectoptionalarray

Form Validation

The form will validate the standard input types, as defined in the form/input/map.js file. Here you can extend the validation and add your own custom validation rules.

// Select a named validation rule from the input map.
const inputs = {
  password: {
    label: 'Password',
    type: 'password',
    required: true,
    validation: { complex: true }
  }
};

Form Submission

When your form is submitted, Gravity will optimise the request and only send the name/value pairs. On the server, you can access a submitted value using:

req.body.email

Form Errors

To show an error on a specific form input, throw an error on the server with an inputError key and the input name.

throw ({ inputError: 'email', message: `You're already registered` });

Payment Form

To create a Stripe payment form, use the <PaymentForm> component. This is a standard form (as above) wrapped in a Stripe provider.

Example

import { Form } from 'components/lib';

function Example({ ...props }){

  return (
    <Form 
      inputs={{
        name: {
         label: 'Your name',
         type: 'text',
         required: true,
         description: 'Your full name',
         placeholder: 'Jon Smith',
         errorMessage: 'Please enter your name',
        },
        email: {
         label: 'Email address',
         type: 'email',
         required: true,
        },
        age: {
         label: 'Age',
         type: 'number',
         min: 18,
         max: 65,
         required: false,
        },
        gender: {
         label: 'Gender',
         type: 'radio',
         options: ['male', 'female'],
         required: true,
        },
        plan: {
         label: 'Billing Plan',
         type: 'select',
         options: [
          { value: 'plan_startup', label: 'Startup' },
          { value: 'plan_enterprise', label: 'Enterprise' }
         ],
         defaultValue: 'plan_startup',
         required: true,
       } 
      }}
      url='/api/user'
      method='PATCH'
      buttonText='Submit'
      callback={(res) => console.log(res)}
    />
  );
}

Notes

  • The Form component uses the useForm and Controller from react-hook-form for form management and validation.
  • The inputs prop defines the form inputs and their configurations.
  • The buttonText prop specifies the text for the submit button.
  • The callback prop is a function executed on successful form submission.
  • The destructive prop sets the submit button color to red.
  • The submitOnChange prop submits the form on each change.
  • The url and method props define the endpoint and HTTP method for form submission.
  • The Form component also includes support for Stripe payments through the PaymentForm component.
  • For more details, refer to the Shadcn Form documentation.