1
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で子コンポーネントにPropsを渡すときに{}を使う理由

Posted at

はじめに

Reactを使っているときによく関数コンポーネントの引数をブロック({})にせずエラーが出がちでした。
そもそもなんでここでブロックを使用しているかを理解したらエラーも減るのでは?と思い調べてみました。

ブロックの理由

前提:分割代入

const obj = { name: 'John', age: 30 };

// オブジェクトの分割代入
const { name, age } = obj;

console.log(name); // 'John'
console.log(age);  // 30

上記のような代入方法を分割代入というそうです。

const { name, age } = obj;
の箇所についてはオブジェクトのキーを指定します。

ちなみに、キー以外を指定するとundefinedになります。

const obj = { name: 'John', age: 30 };

// 正しいプロパティ名を使った場合
const { name, age } = obj;

console.log(name); // 'John'
console.log(age);  // 30

// 存在しないプロパティ名を使った場合
const { a, b } = obj;

console.log(a); // undefined
console.log(b); // undefined

ブロックを使わないpropsの受け渡し

propsを受け渡す際に、ブロックを使わない方法も有るようです。
こちらをベースに考えたほうがわかりやすそうなので記載します。

// props の型定義
type UserProfileProps = {
  name: string;
  age: number;
};

const userProfile: React.FC<UserProfileProps> = (props) => {
  return (
    <div>
      <h1>{props.name}</h1>
      <p>年齢: {props.age}</p>
    </div>
  );
};

// 使用例
const App = () => {
  return <userProfile name="John" age={30} />;
};

上記のようにこれだと{props.name}のように、
コードが冗長になりやすいのであまり使われていないようです。

ブロックを使ったPropsの受け渡し

最後によくみるブロックを使ったPropsの受け渡し例です。

// props の型定義
type UserProfileProps = {
  name: string;
  age: number;
};

const userProfile: React.FC<UserProfileProps> = ({ name, age }) => {
  return (
    <div>
      <h1>{name}</h1>
      <p>年齢: {age}</p>
    </div>
  );
};

// 使用例
const App = () => {
  return <userProfile name="John" age={30} />;
};

ここまで来たらなんとなくわかるかと思うのですが、
Propsオブジェクトの中身を分割代入の仕組みを使って取り出しています。
この場合Propsオブジェクトは以下のようになっています。

UserProps = {
  name: "John",
  age: 30,
}

上記のオブジェクトからnameキーに該当するvalueであるところの"John"と
ageキーに該当するvalueであるところの30を、name,ageに代入している
という感じです。

補足

UserPropsはいつ作られるねんとおもったのですが、
return <userProfile name="John" age={30} />;
↑の記述をもとに、コンポーネントがレンダリングされるタイミングでReactによって自動的に作成される仕様になっているようです。

おわりに

React使う上でもJavaScriptの基礎はちゃんと抑えておく必要が有ることを再確認しました。
これでエラーが減ることを願って…

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