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

More than 3 years have passed since last update.

【React】配列を繰り返し処理で回して props に渡してみる

Last updated at Posted at 2020-11-28

はじめに

React を習得するまでの軌跡をメモっていく備忘録的な記事です。

配列を繰り返し処理で回して props に渡してみる

defaultPropsを使ってpropsに値が入らなかった時のデフォルトも設定してみました。

index.js
import React from 'react';
import ReactDOM from 'react-dom';

// User に入れる用のデータ
const profiles = [
  { name: '太郎', age: 10 },
  { age: 30 },
  { name: '花子', age: 25 },
  { name: '太郎' },
]

const User = (props) => {
  return (
    <p>私の名前は{props.name}で、年齢は{props.age}です。</p>
  )
};

// 値がなかった時のデフォルトを設定
User.defaultProps = {
  name: '名無し',
  age: 20
};

const Users = () => {
  return (
    <div>
      // map を使って profiles から User を繰り返し処理で出力
      {profiles.map((profile) => {
        return <User name={profile.name} age={profile.age}/>
      })}
    </div>
  )
};

ReactDOM.render(
    <Users />,
  document.getElementById('root')
);

スクリーンショット 2020-11-29 0.28.44.png

表示成功

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