Tutorial of the basics: React integration

For this short tutorial, we will need the React adapter, as well as a theme:

npm install @phormal/react @phormal/theme-basic

We will create a form with four input fields. The paymentMethod radio group will be rendered with three different options. The name field will be a required field, and have a minimum length of 3 characters. The email field will also be required, and has to contain a valid email address. Lastly, there will be a checkbox for subscribing to a newsletter.

Code

import {useLength, useEmail, useRequired} from '@phormal/core'
import {useForm, FormContent} from '@phormal/react'
import '@phormal/theme-basic/dist/index.css'
import {useState} from 'react'
 
export default function PhormalExample() {
  const formFields = {
    paymentMethod: {
      type: 'radiogroup',
      label: 'Payment Method',
      value: 'paypal',
      options: [
        {label: 'PayPal', value: 'paypal'},
        {label: 'Credit card', value: 'creditcard'},
        {label: 'Klarna', value: 'klarna'},
      ]
    },
    name: {
      label: 'Name',
      hooks: [useRequired(), useLength(3)]
    },
    email: {
      label: 'Email',
      hooks: [useRequired(), useEmail()]
    },
    newsletter: {
      type: 'checkbox',
      label: 'Newsletter',
      value: true
    },
  }
  const formInstance = useForm(formFields)
 
  const getValues = () => {
    console.log(formInstance.$values()) // Logs the values of all form fields
  }
 
  const validate = () => {
    const formIsValid = formInstance.$validate()
    console.log(formIsValid) // Logs true if all fields are valid, false otherwise
  }
 
  return (
    <>
      <main>
        <div className={'container'}>
          <h1>Phormal</h1>
 
          <FormContent instance={formInstance} />
        </div>
      </main>
    </>
  )
}

Result


Example repo

If you want to play around with this code locally, you can clone this repo: https://github.com/phormal/example-react (opens in a new tab)

Last updated on January 21, 2023