0
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 useStateでオブジェクトを扱う

Posted at

useState()フックでオブジェクトを作ります

App.js
const [post, setPost] = useState(
    {
      name: "mario",
      age: 5,
    }
  )

オブジェクトを更新する

App.js
import { useState } from 'react'
import './App.css'

function App() {

  const [post, setPost] = useState(
    {
      name: "mario",
      age: 5,
    }
  )

  // ageプロパティを更新する
  const handleClick = () => {
    setPost({ ...post, age: post.age + 1 });
  }

  // nameプロパティを更新する
  const handleChange = (event) => {
    const newName = event.target.value
    setPost({ ...post, name: newName });
  }

  return (
    <div className="App">
      <h1>Hello</h1>
      <button onClick={handleClick}>+</button>
      <p></p>
      <input
        type="text"
        placeholder='Input something...'
        value={post.name}
        onChange={handleChange} />
        {/* オブジェクトを参照 */}
      <p>{JSON.stringify(post, null, '\t')}</p>
    </div>
  )
}

export default App

結果

2022-06-24_22h50_45.gif

0
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
0
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?