Closed1

【material ui react-hook-form Next.js】オブジェクト空判定による動的送信ボタンの作成方法

hirohiro

何について書く?

  • 【material ui react-hook-form Next.js】オブジェクト空判定による動的送信ボタンの作成方法

内容

  • まず結論
import { Button, FormControl, TextField } from '@material-ui/core'
import Typography from '@material-ui/core/Typography'
import React from 'react'
import { useForm } from 'react-hook-form'

const Form = () => {

  const { register, handleSubmit, errors } = useForm({
    mode: 'all',
  })

  return (
          <form onSubmit={handleSubmit(submit)}>
                <FormControl fullWidth>
                  <TextField
                    name="test"
                    inputRef={register({ required: true })}
                    error={Boolean(errors.name)}
                    variant="outlined"
                  />
                </FormControl>
                <Button type='submit' variant="contained" fullWidth disabled={!!Object.keys(errors).length}>
                  <Typography variant="button">送信する</Typography>
                </Button>
          </form>
  )
}

export default Form
  • material-uiのButtonにdisabled属性が準備されておりこれがtrueであればグレーアウトされる仕組み
  • なのでそこへreact-hook-formのerrorsがあるかどうか(バリデーションエラーの有無)を確認することで動的に送信ボタンをグレーアウトできるようになる。それが<Button type='submit' variant="contained" fullWidth disabled={!!Object.keys(errors).length}>この部分

参考サイト

このスクラップは2022/04/17にクローズされました