ricardocanelas / useForm-example

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Getting Started with Create React App

This project was bootstrapped with Create React App.

See the example - https://ricardocanelas.github.io/useForm-example/

Example

import useForm from './useForm'

function MyComponent() {
  const { values, errors, touched, handleChange, handleSubmit } = useForm({
    initialValues: {
      firstname: '',
    },
    schema: {
      firstname: {
        required: 'This field is required',
        maxLength: 10,
        validate: (value) => {
          return value.length <= 4 ? 'The field must be at least 5 characters.' : true
        },
      },
    },
    onSubmit: () => {
      console.log('Ready to send to the backend...', { values })
    },
  })

  return (
    <form onSubmit={handleSubmit}>
      <div className="flex flex-col">
        <label>First Name:</label>
        <input type="text" name="firstname" value={values.firstname} onChange={handleChange} />
        {errors.firstname && touched.firstname && <span className="invalid">{errors.firstname}</span>}
      </div>
      <button type="submit">submit</button>
    </form>
  )
}

export default MyComponent

About


Languages

Language:JavaScript 68.4%Language:HTML 22.0%Language:CSS 9.5%