ブログの投稿ログ

2021年
9月
8月
7月
6月

初めてのREACT-v7

オブジェクトの出力

今回はオブジェクトを取得して、表示してみたいと思います。

JSX,REACT,REACT DOMが既に入っているこちらのIDEを使って一緒に進めていくとやりやすいです。 https://jscomplete.com/playground

今回のコード

const testData = [
    {name: "Dan Abramov", avatar_url: "https://avatars0.githubusercontent.com/u/810438?v=4", company: "@facebook"},
    {name: "Sophie Alpert", avatar_url: "https://avatars2.githubusercontent.com/u/6820?v=4", company: "Humu"},
    {name: "Sebastian Markbåge", avatar_url: "https://avatars2.githubusercontent.com/u/63648?v=4", company: "Facebook"},
];

const CardList = (props) => (
  <div>
    {testData.map(profile => <Card {...profile}/>)}
  </div>
);

class Card extends React.Component {
	render() {
    const profile = this.props;
  	return (
    	<div className="github-profile">
    	  <img src={profile.avatar_url} />
        <div className="info">
          <div className="name">{profile.name}</div>
          <div className="company">{profile.company}</div>
        </div>
    	</div>
    );
  }
}

class App extends React.Component {
	render() {
  	return (
    	<div>
    	  <div className="header">{this.props.title}</div>
        <CardList />
    	</div>
    );
  }	
}

ReactDOM.render(
	<App title="The GitHub Cards App" />,
  mountNode,
);

## 配列を取得 ``` class Card extends React.Component { render() { const profile = testData[0]; return (
{profile.name}
{profile.company}
); } } ``` まず最初にCardコンポーネントからみていきましょう。 最終的にprofileの値はpropsから受けとって複数枚表示したいのですが、 このようにtestData[0]からとるとtestData配列の1番目を取得することが確認できます。 このままでは1つしか表示できないので再利用できるようにしていきましょう。
## 複数のカードを表示
const CardList = (props) => (
  <div>
    <Card {...testData[0]} />
    <Card {...testData[1]} />
  </div>
);

class Card extends React.Component {
	render() {
    const profile = this.props;
  	return (
    	<div className="github-profile">
    	  <img src={profile.avatar_url} />
        <div className="info">
          <div className="name">{profile.name}</div>
          <div className="company">{profile.company}</div>
        </div>
    	</div>
    );
  }
}

CardListとCardコンポーネントを上記のようにしてみましょう。
propsを保持するオブジェクトを取得してそれらをカードコンポーネント内に広げるような形になっています。
CardListの{...testData[0]}ですがスプレッド演算子という物になります。
このようなオブジェクト内で使用するとそのオブジェクトの全てのプロパティがコンポーネントのpropsとなります。 そしてCardの中の変数profileはthis.propsにすることでtestDataの値が使えるようになります。

より簡潔にするには

const CardList = (props) => (
  <div>
    {testData.map(profile => <Card {...profile}/>)}
  </div>
);

testDataのようにオブジェクトの配列を取得し、カード要素にマッピングした物が上記になります。 testDataは配列なので、別の配列にmapすることができます。これにより配列ないのオブジェクト一つ一つを取り出すことができます。 そして、このマップされたカード要素のpropsとしてマップから公開されたプロファイル変数を展開することができるのです。