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

はじめに

配列やオブジェトの値を簡単に展開できるスプレッド構文について勉強したので、備忘録も兼ねて本記事を作成しています。

スプレッド構文とは?

スプレッド構文とは、配列やオブジェクトの要素を展開するための構文です。
三つのドット ... を使用し配列やオブジェクトを...array...object を展開します。
pushなどの破壊的な変更を加えることなく、新しい要素の作成を行うことができ便利です。

サンプル

配列とオブジェクトの場合でスプレッド構文を使ってみます。

配列の場合

const array1 = [1, 2, 3];
const array2 = [...array1, 4, 5];
console.log(array2); // [1, 2, 3, 4, 5]

オブジェクトの場合

const obj1 = { key1: 'hoge1', key2: 'hoge2' };
const obj2 = { ...obj1, key3: 'hoge3' };
console.log(obj2); // { key1: 'hoge1', key2: 'hoge2', key3: 'hoge3' }

スプレッド構文を使った状態変数の更新

下記の例では useState フックでオブジェクトを作成し、updateUser 関数でプロパティ名と更新後の値を受け取り、状態変数 user を更新します。
この関数ではスプレッド構文を利用して、既存の状態を維持しながら指定されたプロパティだけを更新します。

App.tsx
import { useState } from "react";
import './App.css'

interface User {
  name: string;
  sports: string;
  food: string;
}

const UserProfile = () => {
  const [user, setUser] = useState<User>({
    name: 'hogeName',
    sports: 'baseball',
    food: 'apple'
  });

  const updateUser = (key: keyof User, value: string) => {
    setUser(prevUser => ({
      ...prevUser,
      [key]: value
    }));
  };

  return (
    <div className="main">
      <h1>{user.name}</h1>
      <h1>{user.sports}</h1>
      <h1>{user.food}</h1>
      <button onClick={() => updateUser('name', 'TAROU')}>名前更新</button>
      <button onClick={() => updateUser('sports', 'soccer')}>スポーツ更新</button>
      <button onClick={() => updateUser('food', 'onigiri')}>好きな食べ物更新</button>
    </div>
  );
}

export default UserProfile;
App.css
App.css
body {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.main {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

button {
  margin: 10px 0;
}

動作確認

サーバを立ち上げて動作を確認します。

npm run dev

download.gif

参考

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