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(
    [
      "apple 🍎",
      "banana 🍌",
      "apple 🍎"
    ]
  )

オブジェクトを更新する

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

function App() {

  const [fruit, setFruit] = useState("")

  // 配列オブジェクト
  const [post, setPost] = useState(
    [
      "apple 🍎",
      "banana 🍌",
      "apple 🍎"
    ]
  )

  // 入力した文字をfruitに入れる
  const handleChange = (event) => {
    setFruit(event.target.value);
  }

  // 配列に追加
  const handleAddToArray = () => {
    setPost((prevState) => ([...prevState, fruit]));
    setFruit("")
  }

  // filter()を使ってbananaを削除
  const deleteArray = () => {
    setPost((prevState) => prevState.filter((value) => value !== "banana 🍌"))
  }

  // filter()を使ってappleを残す
  const findApple = () => {
    setPost((prevState) => prevState.filter((value) => value === "apple 🍎"))
  }

  return (
    <div className="App">
      <h1>Hello</h1>
      <input
        type="text"
        placeholder='Input something...'
        value={fruit}
        onChange={handleChange} />
      <p></p>
      <button onClick={handleAddToArray}>Add to Array 🧺</button>
      <br />
      <button onClick={deleteArray}>Delete Banana 🍌</button>
      <br />
      <button onClick={findApple}>Find Apple 🍎</button>

      {/* 配列オブジェクトを参照 */}
      <p>{JSON.stringify(post, null, '\t')}</p>
    </div>
  )
}

export default App

結果

2022-06-24_23h48_14.gif

0
1
2

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?