今回はオブジェクトを取得して、表示してみたいと思います。
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,
);
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としてマップから公開されたプロファイル変数を展開することができるのです。