0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

chakra-ui & react-hook-form サンプル

Posted at

Form Component

HookForm.tsx

HookForm.tsx
import * as React from 'react'
import { useForm } from 'react-hook-form'
import { Input, Button } from '@chakra-ui/react'
import { FormErrorMessage, FormLabel, FormControl } from '@chakra-ui/react'

type FormData = {
  firstName: string
  lastName: string
}

export function HookForm() {
  //
  const {
    register,
    handleSubmit,
    formState,
    formState: { errors },
  } = useForm<FormData>({
    mode: 'all',
  })

  // const onSubmit = handleSubmit((data) => console.log(data))

  function onSubmit(values) {
    return new Promise(() => {
      setTimeout(() => {
        alert(JSON.stringify(values, null, 2))
      }, 1000)
    })
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <FormControl id="firstName" isInvalid={!!errors.firstName} isRequired>
        <FormLabel>First Name</FormLabel>
        <Input placeholder="first name" {...register('firstName', { required: true })} />
        <FormErrorMessage>{errors.firstName && 'First name is required'}</FormErrorMessage>
      </FormControl>

      <FormControl id="lastName" isInvalid={!!errors.lastName} isRequired>
        <FormLabel>Last Name</FormLabel>
        <Input placeholder="last name" {...register('lastName', { required: true })} />
        <FormErrorMessage>{errors.lastName && 'Last name is required'}</FormErrorMessage>
      </FormControl>

      <Button mt={4} colorScheme="teal" isLoading={formState.isSubmitting} type="submit">
        Submit
      </Button>
    </form>
  )
}

stories

HookForm.stories.tsx

import React from 'react'

import { Story, Meta } from '@storybook/react/types-6-0'
import { HookForm } from '../../../components/example/validation/HookForm'

export default {
  title: 'Example/HookForm',
  component: HookForm,
} as Meta

export const HookFormSample: Story = (args) => <HookForm {...args} />

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?