分割代入と残余引数でオブジェクトの特定のプロパティ以外を全て取り出す

分割代入と残余引数を使えば、オブジェクトから「特定のプロパティ以外」を全て取り出すことができます。

const profile = {
  id: 1,
  name: "hoge",
  age: 30,
  gender: "man",
  height: 165,
  weight: 55,
  bloodType: "O"
}

const {id, ...newProfile} = profile;
console.log(newProfile);
// {"name": "hoge", "age": 30, "gender": "man", "height": 165, "weight": 55, "bloodType": "O"} 

上の例では、オブジェクトprofileからidを分割代入で取り出し、それ以外のプロパティは残余引数を使ってnewProfileで取り出しています。

Reactでは、「propsの特定のプロパティ以外をそのまま別のコンポーネントに渡す」ときなんかに使えます。

以下の例では、HogeButtonコンポーネントにpropsでbuttonNameonClickdisabledを渡しています。

HogeButtonコンポーネントではbuttonNameを分割代入で取り出し、それ以外は残余引数でhogeButtonPropsとして取り出しています。

そして、Buttonコンポーネントに対してbuttonNameを渡し、それ以外はhogeButtonPropsをスプレッド構文で展開して渡しています。

"use client"

import HogeButton from "@/components/HogeButton";

export default function Home() {
  return (
    <HogeButton
      buttonName="hoge"
      onClick={() => {
        alert("hoge");
      }}
      disabled={false}
    />
  );
}
import { ButtonHTMLAttributes } from "react";
import Button from "./Button";

type HogeButton = {
  buttonName: string;
} & ButtonHTMLAttributes<HTMLButtonElement>;

const HogeButton = (props: HogeButton) => {
  const { buttonName, ...hogeButtonProps } = props;
  return <Button buttonName={buttonName} {...hogeButtonProps} />;
};

export default HogeButton;
import { ButtonHTMLAttributes } from "react";

type Button = { buttonName: string } & ButtonHTMLAttributes<HTMLButtonElement>;

const Button = (props: Button) => {
  const { buttonName, ...buttonProps } = props;
  return <button {...buttonProps}>{buttonName}</button>;
};

export default Button;

↓↓「にほんブログ村」のランキングに参加しています。少しでも面白い、参考になったとか思われたらポチッとしていただけると嬉しいです!
にほんブログ村 IT技術ブログへ
にほんブログ村