skip to Main Content

I need to create a form in nextjs, in plain react some time ago I used to manage the state of each input of the form by using an useState hook, now I have seen in the official nextjs documentation that the good practice is do things like this, where user only submit the form and you validate the inputs on the function onSubmit, import React, { useState, FormEvent } from ‘react’

export default function Page() {
  const [isLoading, setIsLoading] = useState<boolean>(false)
 
  async function onSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setIsLoading(true) // Set loading to true when the request starts
 
    try {
      const formData = new FormData(event.currentTarget)
      const response = await fetch('/api/submit', {
        method: 'POST',
        body: formData,
      })
 
      // Handle response if necessary
      const data = await response.json()
      // ...
    } catch (error) {
      // Handle error if necessary
      console.error(error)
    } finally {
      setIsLoading(false) // Set loading to false when the request completes
    }
  }
 
  return (
    <form onSubmit={onSubmit}>
      <input type="text" name="name" />
      <button type="submit" disabled={isLoading}>
        {isLoading ? 'Loading...' : 'Submit'}
      </button>
    </form>
  )
}

Now I would like to have for example an input called phone number, I need to validate the content of it, I would like to have the forms green border while the inputed value is correct and red is incorrect, for do this i need a client component that uses useState right? I can’t do it with a server component for better performance, also what about error handling, what is the best practice for handling errors on each field?

I thought to make a part of the form client component and a part of the form server component for better performance.

2

Answers


  1. Your example is definitely a better pattern I would say.
    You can also checkout libraries like react-hook-form and zod for validation. It can help saving a lot of time, although you might want to watch out for compatibility with SSR

    Login or Signup to reply.
  2. Definitely if you want to handle the errors on onChange event, then you have to use the useState hook, which makes the components client side. Other then that, there are libraries like React Hook Form or Formik that could help with validation on value change. They provide inbuilt error handling mechanisms to handle errors for each field, with the functionality to have custom error messages.

    However, there is another method if you want the values to be validated on the click of button. We can acheive that using useRef. Here you can create multiple refs for the form elements and attach it to each input field. Later on click of submit, you can get the values using ref.current.value. The biggest usecase of this is, you can prevent rerendering of component on each keystroke. The values will be stored in the variable and then can be validated on the Submit button.

    React hook form

    Formik

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search