Create image View show more - javascript

I want to create a view like this one:
I am using a Flatlist in which all the data is coming including these thumbnails. This thumbnail is a array of objects from where I fetch image's name and display.
I want to use this inside a FlatList where all my data is coming or I just need a dummy code to implement this feature in react native
Right now I am trying to implement it like this:
<View style={{flexDirection:'row'}}>
{data.gallery.map((each,index)=>{
console.log('thubnails ******* ', each);
<Image source={{uri: Connection.getMedia()+each.name}} style={{height:Constants.BaseStyle.DEVICE_HEIGHT/100 * 10, width:Constants.BaseStyle.DEVICE_WIDTH/100 * 10}} resizeMode='stretch' />
})}
</View>
Inside data.gallary all the thumbnails are present and data is coming from props.

Sample code from the above details.
Inside render:
<FlatList
data={this.props.sampleData} // sample data should be a array of objects
renderItem={this.renderImage}
/>
renderImage function:
renderImage = ({ item }) => (
<Image source={{ uri: Connection.getMedia()+item.name }}
style={{height:Constants.BaseStyle.DEVICE_HEIGHT/100 * 10,
width:Constants.BaseStyle.DEVICE_WIDTH/100 * 10}}
resizeMode='stretch'
/>
);
You can also use Dimensions for getting device height and width.

Related

Pass Custom Relative Image source to Image Tag React Native

I am trying to create a custom component in React Native which contains an Image tag with a custom source to be passed to it. The problem now is, I am getting an error that says Invalid call at line 17: require(imageSrc).
This is my GoalButton component code below:
const GoalButton = ({
buttonStyle,
onPress,
text,
imageSrc,
imageStyle,
textStyle,
}) => {
return (
<TouchableOpacity onPress={onPress}>
<View style={buttonStyle}>
<Image style={imageStyle} source={require(imageSrc)} />
// Above line is Line 17
<Text style={textStyle}>{text}</Text>
</View>
</TouchableOpacity>
);
};
GoalButton.defaultProps = {
buttonStyle: styles.buttonStyle,
onPress: () => null,
imageStyle: styles.imageStyle,
textStyle: styles.textStyle,
};
export default GoalButton;
And I call it from outside like this:
<GoalButton text={'Meal Plan'} imageSrc={'../assets/images/plate.png'} />;
My question is, is there a way I can pass a relative image URL to the component and access it without any error like I was using it directly on the Image component.
it is not possible, you can looked this,
https://stackoverflow.com/questions/30854232/react-native-image-require-module-using-dynamic-names#:~:text=The%20only%20allowed%20way%20to%20refer%20to%20an%20image%20in%20the%20bundle%20is%20to%20literally%20write%20require(%27image!name-of-the-asset%27)%20in%20the%20source.

React Native FlatList refreshing not working

i got an problem with the refreshing on pull function. The FlatList renders fine, but pull to refresh is not working. This is my current sourcecode:
return (
<View style={GlobalStyles.flex1}>
<FlatList
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl
refreshing={isRefreshing}
onRefresh={() => {
console.log("onRefresh loadVocable");
loadVocables();
}}
/>
}
data={vocables}
keyExtractor={vocable => vocable.id}
onEndReached={() => {
if (!isRefreshing && !endReached) {
loadVocables();
}
}}
renderItem={vocable => (
<TouchableOpacity
onPress={() => {
props.navigation.navigate({ routeName: "editVocable", params: { vocable: vocable.item } });
}}
onLongPress={() => {
handleLongPress(vocable.item.id);
}}>
<Card style={styles.cardStyle}>
<View style={styles.part1}>
<Text style={styles.vocableText}>{vocable.item.wordENG}</Text>
<Text style={styles.vocableText}>{vocable.item.wordDE}</Text>
</View>
<View style={styles.part2}>
<Ionicons name={vocable.item.known ? "md-checkmark-circle" : "md-close-circle"} size={23} color={vocable.item.known ? Colors.success : Colors.danger} />
</View>
</Card>
</TouchableOpacity>
)}
/>
</View>
);
In the official docs is an example that says contentContainerStyle needs to be flex: 1 to know the height, that makes sence to me, so when i set contentContainerStyle with flex 1, refresh on pull works fine, but then i can't scroll anymore in the Flatlist and everthing get very tight, so the style also change then. Does anyone know why this happen?
The first picture is with "contentContainerStyle={{flex: 1}}" and the last one is without contentContainerStyle.
The answer was so easy, I compared a new project (there worked my code) to the one where the problem was and after 5 days I found the little error:
My import was wrong!
I imported FlatList like this:
import { FlatList } from "react-native-gesture-handler";
But it needs to get imported from React-Native so like this:
import { FlatList } from "react-native";
Thanks to #The1993, without the hint to compare the projects, maybe I would stuck forever on this error :D In the future I will compare working files to find any error!
contentContainerStyle is used to style inner content e.g items alignments, padding, etc
style is used to align its height and relations
You can replace style={{flex: 1}} instead of contentContainerStyle or wrap the parent element with flex: 1

Possible to pass a changing array to a stateless component?

So let's say I have a stateless component. I want this component to
display a static title but also map through an array that's
being passed in. I only want to do it this way due to styling
issues. Is this possible or is there another way to go about this?
Thanks!
const ListTitle = ({ style, title, icon, checkedItems, onPressExpand }) => (
<View>
<TouchableOpacity onPress={onPressExpand}>
<View style={ [style, baseStyles.touchableList] }>
<Text>{title}</Text>
{icon}
</View>
</TouchableOpacity>
{
checkedItems.map((item, i) => (
<View>
<Text>{item}</Text>
</View>
))
}
</View>
)
checkedItems is the array I want to pass in. {checkedItems}.map doesn't look right but neither does the way I tried. I'm starting to think this isn't possible but wanted to know what others have to say.

Arrange 3 images in a row in React Native

I have just started working on a React Native project and I got stuck. I need to display a listof images from an API. The API only gives image urls that I can use like this:
<Image
style={{width: 50, height: 50}}
source={{uri: 'https://avatars0.githubusercontent.com/u/13102253?s=460&v=4'}}
/>
The image count is dynamic but I want to display only 3 images per row. How can I achieve this?
You can use ListView in which you can style it by wrapping it into row like this
and page size will take care of arranging into row
<ListView
contentContainerStyle={styles.list}
dataSource={this.props.yourData} //datasource either props/state only
pageSize={3}
renderRow={(data, rowID, sectionID) => (
<Image
style={{width: 50, height: 50}}
source={{uri: data.path}}/>)} //path here is url that you receive
const styles = StyleSheet.create({
list: {
flexDirection: "row",
flexWrap: "wrap"
}})
The React-Native FlatList is exactly what you need. It accepts a numColumns prop which in your case should be 3.
<FlatList
numColumns={3}
data={yourImagesArray}
renderItem={<YourImageComponent >}
/>
Each iteration of the data array (which I called here yourImagesArray) is passed to the renderItem (which I called here YourImageComponent) as a data prop. So the render function of YourImageComponent should be something like this:
render() {
const { data } = this.props;
return (
<Image source={{ uri: data.uri }} style={{ width: 50, height: 50 }} />
);
}

React Native Network Image Doesn't Render

The code I am writing is for wordpress.
I have succeed in fetching titles, category IDs and featured media IDs. Then I try to fetch the image uri to display it.
The wired thing is: Every time the post title and category id and author id come very fast, however, the image doesn't show until I press load more (which is built in by Gifted Listview). The requests happen both at "load more" and "ListViewOnFresh", so it should be like this.
I tried to use console.log to output "start loading" and "loading finished" when image starts and ends ending. However, I can see it was never loaded unless I press load more.
Even if it is loaded, if I pull to refresh (call the ListViewOnRefresh), it will disappear again.
I tried also to output dataRows, it has no problem at all, the featured_image is showing the right uri.
I really cannot solve this. Thank you in advance for your help.
var MovieListScreen = React.createClass({
componentDidMount: function() {
Controllers.NavigationControllerIOS("movies_nav").setLeftButtons([{
title: "Categories",
onPress: function() {
Controllers.DrawerControllerIOS("drawer").toggle({side:"left"});
}
}]);
},
renderListViewRow: function(row){
return(
<View >
<TouchableHighlight underlayColor={'#f3f3f2'} onPress={()=>this.selectRow(row)}>
<View style={styles.articleContainer}>
<View style={styles.rowDetailsContainer}>
<Image resizeMode="cover" style={styles.featuredImage}
source={{uri: row.featured_image}}
onLoadStart={() =>{console.log('start loading')}}
onLoadEnd={() => {console.log('loading finished')}}
/>
<Text style={styles.articleTitle}>
{row.title.rendered}
</Text>
<Text style={styles.articleTime} >
Posted by {row.author}, Category: {row.categories[0]}
</Text>
<Text style={styles.articleExcerpt}>
{row.excerpt.rendered}
</Text>
</View>
</View>
</TouchableHighlight>
<View style={styles.separator}/>
<View style={styles.articleActions}>
<Icon style={{flex:1}} name="share-alt" size={20} color="#0088CC" />
<Icon style={{flex:1}} name="thumbs-o-up" size={20} color="#0088CC" />
<Icon style={{flex:1}} name="star-o" size={20} color="#0088CC" />
<View style={{flexDirection:'row',justifyContent:'center',alignItems:'center'}}><Icon style={{flex:1}} name="external-link" size={20} color="#0088CC" /><Text style={{fontSize:15,color:'#0088CC'}}> Read More</Text></View>
</View>
</View>
);
},
listViewOnRefresh: function(page, callback){
var rowsData = [];
var REQUEST_URL = 'http://jo.wtf/wp-json/wp/v2/posts?per_page=10&order=asc&page='+page;
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {responseData.map((obj)=>{
fetch('http://jo.wtf/wp-json/wp/v2/media/'+obj.featured_media)
.then((responseMedia) => responseMedia.json())
.then((responseDataMedia) => {
obj.featured_image= responseDataMedia.guid.rendered;
})
rowsData.push(obj);
console.log(rowsData);
})
callback(rowsData);
return;
})
.done();
},
selectRow: function(row){
var navigationController = Controllers.NavigationControllerIOS("movies_nav");
navigationController.push({
component: "PushedScreen", // the unique ID registered with AppRegistry.registerComponent (required)
backButtonTitle: "", // override the nav bar back button title for the pushed screen (optional)
backButtonHidden: false, // hide the nav bar back button for the pushed screen altogether (optional)
});
},
render: function() {
return (
<RefreshableListView renderRow={(row)=>this.renderListViewRow(row)}
onRefresh={(page, callback)=>this.listViewOnRefresh(page, callback)}
backgroundColor={'#EFEFEF'}
style={styles.listview}/>
);
},
});
i think you should add
style={{width:200,height:300}}
to your Image tag
I have solved this problem in another way.
I tried to rewrite the code with async functions but it didn't help either. I think it is caused by 2 api calls at the same time, although why I cannot do that.
Anyway, I don't want to call one API to fetch the thumbnail ID and then call N APIs to get the url for those thumbnails, so I changed the wordpress API.
Add some code to the function.php file into my theme solved it.
It seems I cannot insert php code here... See here:
http://jo.wtf/adding-extra-fields-to-wp-api-output/

Categories