Reputation: 1742
Hello I'm trying to render a fetch response from server like the following
.then(responseData => {
responseData.map(detail => {
let currIndex = -1;
let k = detail.data.curriculum.reduce((acc, curr) => {
if (curr.type === 'section') {
acc.push({
title: curr.title,
content: [],
id: []
})
currIndex += 1
} else {
acc[currIndex].content.push(curr.title);
acc[currIndex].id.push(curr.id);
}
return acc;
}, []);
console.log(k)
this.setState({ k })
});
});
I'm trying to render a UI like this
But what I'm getting is the name of video contents will be listed one after the other as a list like this
The corresponding code I've tried so far is as below
code
<Content padder style={{ backgroundColor: "#f4f4f4" }}>
{this.state.k.map(detail =>
<View style={st.card}>
<View style={st.cardHeading}>
<Text style={st.headingText}>{detail.title}</Text>
</View>
<ScrollView
horizontal
style={st.cardBody}>
<View style={st.videoContent}>
<View style={st.videoImage}>
<MaterialCommunityIcons name="play-circle-outline" size={25} color="#fff" />
</View>
<Text style={st.subheadingText}>{detail.content}</Text>
</View>
</ScrollView>
</View>
)}
</Content
>
The json data within this.state.k is as follows.I'm trying to render the Title as headingText
and content as videoContent
.Please help me to find a solution.
Upvotes: 3
Views: 3317
Reputation: 21180
It looks like what you are missing is to actually loop through the content or id arrays inside the ScrollView
element. Based on your current data structure, I would suggest doing something like this.
<ScrollView
horizontal
style={st.cardBody}
>
{detail.content.map((contentValue, i) => (
<View style={st.videoContent}>
<View style={st.videoImage}>
<MaterialCommunityIcons
name="play-circle-outline"
size={25}
color="#fff"
/>
</View>
<Text style={st.subheadingText}>
Title: { contentValue }
Id: { detail.id[i] }
</Text>
</View>
))}
</ScrollView>
Note that I added the value from the id
array inside the Text
element, both to illustrate how to access it, but also to show that the data structure makes this quite cumbersome so it might be better to improve that structure, possible like this
.then(responseData => {
responseData.map(detail => {
let currIndex = -1;
const k = detail.data.curriculum.reduce((acc, curr) => {
if (curr.type === 'section') {
acc.push({
title: curr.title,
content: []
})
currIndex += 1
} else {
acc[currIndex].content.push(curr);
}
return acc;
}, []);
this.setState({ k })
});
});
That way you don't have to keep track of the index of the array when mapping and can simple use it like this
{detail.content.map((curr) => (
...
<Text style={st.subheadingText}>
Title: { curr.title }
Id: { curr.id }
</Text>
...
))}
Upvotes: 1