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

ReactにおけるuseState色々

Posted at

はじめに

ReactにおけるuseStateを用いたデータの更新方法をまとめました!

1. 文字列の更新

import { useState } from 'react'

export default function Component() {
  const [name, setName] = useState('文字列')

  return (
    <div>
      <h1>{name}</h1>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
    </div>
  )
}

2. オブジェクトの更新

import { useState } from 'react'

export default function Component() {
  const [user, setUser] = useState({ id: 1, name: '単一オブジェクト' })

  return (
    <div>
      <h1>{user.name}</h1>
      <input
        type="text"
        value={user.name}
        onChange={(e) => setUser({ ...user, name: e.target.value })}
      />
    </div>
  )
}

3. オブジェクト配列の更新

import { useState } from 'react'

export default function Component() {
  const [users, setUsers] = useState([
    { id: 1, name: '配列のオブジェクト1' },
    { id: 2, name: '配列のオブジェクト2' },
    { id: 3, name: '配列のオブジェクト3' },
  ])

  return (
    <div>
      {users.map((user, i) => (
        <div key={user.id}>
          <h1>{user.name}</h1>
          <input
            type="text"
            value={user.name}
            onChange={(e) =>
              setUsers((prevUsers) => {
                prevUsers[i].name = e.target.value
                return [...prevUsers]
              })
            }
          />
        </div>
      ))}
    </div>
  )
}

4. チェックボックスの更新

import { useState } from 'react'

export default function Component() {
  const [checked, setChecked] = useState(false)

  return (
    <input
      type="checkbox"
      checked={checked}
      onChange={(e) => setChecked(e.target.checked)}
    />
  )
}
2
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
2
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?