Reputation: 4502
Currently when user click on a particular topic it returns all the items in an array. However, I would like to pass the key and only return specific item within the object in the map function. I tried passing index as an argument but it doesn't seems to work.
var topicPages = [
{
topic_no: '1',
topic_page_no: '1',
headline: 'Topic 1 headline',
description: 'Topic 1 description comes here...',
first_topic_page: true,
last_topic_page: false
},
{
topic_no: '2',
topic_page_no: '2',
headline: 'Topic 2 headline',
description: 'Topic 2 description comes here...',
first_topic_page: false,
last_topic_page: false
},
{
topic_no: '3',
topic_page_no: '3',
headline: 'Topic 3 headline',
description: 'Topic 3 description comes here...',
first_topic_page: false,
last_topic_page: false
},
{
topic_no: '4',
topic_page_no: '4',
headline: 'Topic 4 headline',
description: 'Topic 4 description comes here...',
first_topic_page: false,
last_topic_page: true
}
];
var SelectedTopicPage = React.createClass({
render: function() {
return (
<div>
{this.props.topicPages.map(function (topicPage) {
return (
<SelectedTopicPageMarkup headline={topicPage.headline} key={topicPage.topic_no}>
{topicPage.description}
</SelectedTopicPageMarkup>
);
})}
</div>
);
}
});
var SelectedTopicPageMarkup = React.createClass({
render: function() {
return (
<div className="topics-page">
<h1>{this.props.headline}</h1>
<p>{this.props.children}</p>
</div>
);
}
});
Upvotes: 2
Views: 17621
Reputation: 89
I believe you have already found what you were looking for but, I saw this question but no answer, still.
You just need to define a variable outside mapping and while mapping, put an if condition to find what you looking for and then equalize the result to the variable outside.
Like,
let tmpItem;
this.state.newOrder.map((mapItem) => {
if (mapItem.id == "99") {
console.log(mapItem)
tmpItem = mapItem;
}
});
Upvotes: 1
Reputation: 2580
It's better to use find
, but it is not supported in all browsers. Use reduce
instead of map
:
var SelectedTopicPage = React.createClass({
render: function() {
var selectedId = this.props.selectedId; // id what you need to find
var topicPage = this.props.topicPages.reduce(function(topic, current) {
return topic.topic_no == selectedId ? current : topic;
}, undefined);
return (
<SelectedTopicPageMarkup headline={topicPage.headline} key={topicPage.topic_no}>
{topicPage.description}
</SelectedTopicPageMarkup>
);
}
});
Upvotes: 2