I have a nested array of "credits"
const credits = [
{
id: 1,
heading: 'Test Organisation',
credits: [
{id: 1, text: 'Joe Bloggs'},
{id: 2, text: 'Jane Bloggs'},
]
},
....
];
I am wanting to print each "header" in a <Text> element, and then subsequently each of their "credits" in a <Text> element.
I have looked at the following already answered questions on how to achieve this, but one is for ReactJS and uses HTML and the other that uses React Native outputs only the opening tag of a view:
Cannot Render Nested Maps In ReactJS
How to use if else condition inside nested map function in react-native?
I am being told there is a syntax error as it is expecting a close parentheses after the end of the first <Text> element.
Here is what I have:
render() {
return (
<ScrollView style={styles.container}>
<View style={styles.centredHighlightHeaderWrapper}>
<Text style={styles.centredHighlightHeader}>
Credits
</Text>
</View>
{
credits.map(item => (
<Text style={styles.centredHeader}>{item.heading}</Text>#Unexpected token -- js error says expecting "," - phpstorm says expecting ")"
{
item.credits.map(credit => (
<Text style={styles.name}>{credit.text}</Text>
))
}
))
}
</ScrollView>
);
}
{
credits.map(item => (
<React.Fragment>
<Text style={styles.centredHeader}>{item.heading}</Text>
{
item.credits.map(credit => (
<Text style={styles.name}>{credit.text}</Text>
))
}
</React.Fragment>
))
}
You can't have adjacent react elements without a container. So I've put them both in a React.Fragment for you
Related
Im trying to map my state , but it allways returns me this error, someone knows how to solve it ?
useEffect(() => {
if (mounted && userForm.length > 0) {
console.log(userForm, 'campos:', userForm.fields);
return;
} else {
setuserForm(JSON.parse(route.params.paramKey));
console.log(userForm);
}
}, [userForm]);
return (
<SafeAreaView style={{flex: 1}}>
<View style={styles.container}>
<Text style={styles.textStyle}>COLLECTION :</Text>
{userForm.length > 0 ? (
userForm.map((item) => (
<Text key={uuid.v4()}>{item.fields}</Text>
))
) : (
<Text key={uuid.v4()}> Loading ...</Text>
)}
</View>
</SafeAreaView>
);
};
what I'm trying to do is render all my fields and then handle the following types.
If I understand you correctly, you are trying to render item.field as node. However, seems that this is an array, so you need to map it one more time.
For example, if it contains strings it might looks like this:
<Text key={uuid.v4()}>{item.fields?.concat('')}</Text>
In case filds contains objects you have to map it to the new component, like this:
<Text key={uuid.v4()}>{item.fields?.map((field, i)=> <div key={i}>{field.someProp}</div>}</Text>
In case you don't know what is inside the fields, check the Network tab in the ChromeDeveloperTools (F12) or use JSON.stringify
I am new in react native and I was trying to use the "react-native-snap-carousel". The carousel is working with the parameters in the "carouselItems" variable as I sent, but the image is not working. I supoused to place it at the Card as a background image, with a short description with the same parameter array, but it is not working.
Can anyone help me to set it?
the array used to fill the cards:
const carouselItems = [
{
title: "Doce",
text: "[TEXTO DESCRITIVO]",
thumbnail: "assets/splash.png",
},
{
title: "Salgado",
text: "[DESCRIÇÃO]",
thumbnail: "assets/splash.png",
},
]
the folder structure is:
homemade-app / assets / splash.png
return (
<View style={styles.item}>
<ParallaxImage
source={{ uri: item.thumbnail }}
containerStyle={styles.imageContainer}
style={styles.image}
parallaxFactor={0.2}
{...parallaxProps}
/>
{item.thumbnail}
<Text style={styles.title} numberOfLines={2}>
{item.title}
</Text>
</View>
)
}
const goForward = () => {
carouselRef.current.snapToNext();
};
return (
<View style={styles.container}>
<TouchableOpacity onPress={goForward}>
<Text>go to next slide</Text>
</TouchableOpacity>
<Carousel
layout={"default"}
ref={ref => carousel = ref}
data={carouselItems}
sliderWidth={screenWidth}
sliderHeight={screenWidth}
itemWidth={screenWidth - 60}
renderItem={renderItem}
onSnapToItem={index => setState({ activeIndex: index })}
hasParallaxImages={true} />
</View>
);
}
I saw the article about how to handle local file with assets, but I still could not make it work properly.
Link to the article: (https://dev.to/fdefreitas/how-to-obtain-a-uri-for-an-image-asset-in-react-native-with-expo-7bm)
If you are using expo. First of all try with a static route remember you need full path not assets/myimage this is wrong, because sometime use it from array give problems like in this question Render images sources from parsed array of objects in react native .
array
const carouselItems = [
{
title: "Doce",
text: "[TEXTO DESCRITIVO]",
thumbnail: require("./../assets/splash.png"),
},
{
title: "Salgado",
text: "[DESCRIÇÃO]",
thumbnail: require("./../assets/splash.png"),
},
]
<ParallaxImage
source={require('#expo/snack-static/yourimage.png')}
...
/>
or put your image in same folder
<ParallaxImage
source={require('./your-image.png')}
...
/>
I'm trying to map an array from state - but confused re the correct syntax - can anyone please advise where i'm going wrong:
This is what I have at the mo:
newsStorys = () => {
return (
{this.state.newsFeed.map((a) => {
<View style={ModalStyles.newsArticle}>
<Text style={ModalStyles.newsDate}>{a.date}</Text>
<Text style={ModalStyles.newsTitle}>{a.title}</Text>
<Text style={ModalStyles.newsDesc}>
{a.story}
</Text>
</View>
}
}
);
};
I'm not sure if that is the whole code of your component, but I can see three things.
If newsFeed is not initialized when component first render (let's say it is undefined yet), then newsFeed.map()will throw an exception.
You are not returning anything from map call. you should write something like this:
newsStorys = () => {
if (!this.state.newsFeed) return null;
return this.state.newsFeed.map((a) => ({ // <--- note the parentheses here, you don't have it
<View style={ModalStyles.newsArticle}>
<Text style={ModalStyles.newsDate}>{a.date}</Text>
<Text style={ModalStyles.newsTitle}>{a.title}</Text>
<Text style={ModalStyles.newsDesc}>
{a.story}
</Text>
</View>
});
);
};
If you want to avoid the parentheses, then you need to explicitly return something, like this:
this.state.newsFeed.map((a) => {
return (
<View style={ModalStyles.newsArticle}>
<Text style={ModalStyles.newsDate}>{a.date}</Text>
<Text style={ModalStyles.newsTitle}>{a.title}</Text>
<Text style={ModalStyles.newsDesc}>
{a.story}
</Text>
</View>
);
});
It is possible that you need an extra view to wrap the list of views returned by map.
Also you need to provide a unique key to each view, so React can keep track on them.
<View style={ModalStyles.newsArticle} key={'nome unique value'}>
...
</View>
Finally I think it would be better using a FlatList instead of map.
Cheers!
Had a play and a good dig around the web and found the syntax answer: (Thanks to Bruno for the Key and pointers).
newsStorys = () => {
return this.state.newsFeed.map((value, index) => {
return (
<View style={ModalStyles.newsArticle} key={index}>
<Text style={ModalStyles.newsDate}>{value.date}</Text>
<Text style={ModalStyles.newsTitle}>{value.title}</Text>
<Text style={ModalStyles.newsDesc}>{value.story}</Text>
</View>
);
});
};
Try this
newsStorys = () => (
this.state.newsFeed.map(({ date, story, title }, index) =>
<View key={`news-${index}`} style={ModalStyles.newsArticle}>
<Text style={ModalStyles.newsDate}>{date}</Text>
<Text style={ModalStyles.newsTitle}>{title}</Text>
<Text style={ModalStyles.newsDesc}>{story}</Text>
</View>
));
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.
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>
...
))}
I am trying some react native code which is as follows , I want to set the static images to an image view as follows but it doesn't load
const items = [
{ name: './images/home.png', code: '#1abc9c' }, { name: './images/home.png', code: '#2ecc71' },
{ name: './images/home.png', code: '#3498db' }, { name: './images/home.png', code: '#9b59b6' }
];
return (
<ImageBackground
source={require('./images/marble.jpg')}
style={styles.backgroundImage}>
<GridView
itemDimension={130}
items={items}
style={styles.gridView}
renderItem={item => (
<View style={[styles.itemContainer, { backgroundColor: item.code }]}>
<Image source={require(item.name)}></Image>
</View>
)}
/>
</ImageBackground>
);
Error I get is
calls to require expect exactly 1 string literal argument, but this was found: require(item.name).
Ofcourse I am new to react native so kindly ignore my missed terminology
You try like this
const items = [{ name: require('./images/home.png'), code: '#1abc9c' },{...}]
then
<Image source={item.name}></Image>