2
1

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 1 year has passed since last update.

React(Next.js)、Typescriptでcheckboxのchangeイベントを使うときの注意点

Posted at

React(Next.js)、TypeScript にてcheckboxのchangeイベントを扱うときに、エラーが出たので、解決方法をメモしておきます。

エラーの内容

Argument of type 'string' is not assignable to parameter of type 'boolean'.

修正したコード

handleChangeCheckedメソッドの引数を、e.target.valueからe.target.checkedに修正しました。

子のコンポーネント
inputCheckboxChild.tsx
import React from 'react'
interface InputProps {
  checked: boolean
  handleChange: (event: React.ChangeEvent<HTMLInputElement>) => void
}
export const InputCheckboxChild = ({ checked, handleChange }: InputProps) => {
  return (
    <>
      <input
        type="checkbox"
        checked={checked}
        onChange={(e) => handleChange(e)}
      />
    </>
  )
}

inputCheckboxParent.tsx
import React, { useState } from 'react'
import { InputCheckboxChild } from '../components/InputCheckboxChild'

export default function Test() {
  const [checkedData, setCheckedData] = useState(false)
  const handleChangeChecked = (chk: boolean) => {
    setCheckedData(chk)
  }
  return (
    <div>
      <InputCheckboxChild
        checked={checkedData}
        handleChange={(e) => handleChangeChecked(e.target.checked)}
      />
    </div>
  )
}


type="text"の時には、value属性を指定しせずにe.target.valueを使っていたために解決に時間がかかりました。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?