How to handle dynamic require images react native - reactjs

i saved images to MongoDb with multer to path /uploads in my local static folder.
the object that i get from the data base when i get images look like :
Array [
Object {
"_id": "5fc4581a1b858e93a65136e7",
"desc": "19",
"image": "uploads/a2.jpg",
},
Object {
"_id": "5fc4584a873e544138a10a33",
"desc": "19",
"image": "uploads/a2.jpg",
},
]
now i want to show the array with desc and image so i defined a flat list and try to do:
<FlatList
numColumns={numColumns}
data={s}
renderItem={({ item, index }) => (
console.log("http://localhost:8080/" + item.image),
(
<View style={styles.imagecontainer}>
<Text>{item.desc}</Text>
{Object.keys(s).length === 0 ? null : (
<Image style={styles.image} source=
{require(`../../server/${item.image}`)} />/////////here is the problem
)}
</View>
)
)}
keyExtractor={(item, index) => index.toString()}
/>
now I understand that require should get only static string and not variables,
the question is how can I handle this to show the images and desc dynamically based on the array?
I read a lot of it on the internet but Dont find the answer for this...
I need somehow to convert the objects that I get and replace the image prop that gave me "uploads/a2.jpg" to {require(../../server/**here to put the image for each object**) but I Dont find a way to do that.

I faced the same issue, the only way I found it was to save images' IDs returned by the require() function.
console.log(require("image path"));
// return a number for example 5

Related

How to Make Carousel View of Screens without Navigation in React Native

I would like to implement a dynamic carousel view of screens (similar to Swiper). I was thinking of creating a View with conditional rendering that would display a screen by selectedId corresponding to each screen, but that would cause a re-render on every screen, unless I have a state for each one of them.
Is there any better solution to make a carousel view of screens without using navigation and keep the data on the screen saved?
I have used react-native-progress-steps for this solution. I have modified the config file a little and wrote a dummy data template for it.
Dummy data:
const reviewData = [
{
id: "1",
serviceID: 0,
},
{
id: "2",
serviceID: 1,
},
{
id: "3",
serviceID: 2,
},
];
render (disregard colors):
<View style={styles.container}>
<ProgressSteps
activeStepIconColor={defaultColors.white}
completedProgressBarColor={settings.colors.primary}
progressBarColor={defaultColors.light}
activeStepIconBorderColor={settings.colors.primary}
completedStepIconColor={settings.colors.primary}
disabledStepIconColor={defaultColors.light}
activeStepNumColor={defaultColors.dark}
disabledStepNumColor={defaultColors.mediumLight}
>
{reviewData.map((item, index) => (
<ProgressStep
nextBtnStyle={styles.nextButtonStyle}
previousBtnStyle={
index === 0
? styles.disabledButton
: styles.prevButtonStyle
}
nextBtnTextStyle={styles.nextButtonTextStyle}
previousBtnTextStyle={styles.prevButtonTextStyle}
previousBtnText={`Назад`}
nextBtnText={`Дальше`}
finishBtnText={`Завершить`}
previousBtnDisabled={index === 0 ? true : false}
>
<View style={{ alignItems: "left" }}>
<AppText>
{item.serviceID},{index}
</AppText>
</View>
</ProgressStep>
))}
</ProgressSteps>
</View>
I am satisfied with the solution, but if you have any other solutions, please let me know :)

React Native - cannot access data from Array inside Array from json file

So I have typical json result from Google maps api
"html_attributions" : [],
"next_page_token" : "CqQCFgEAAL2fPrvHrkhgi11wNUC40-FEYJ93rH1Bo9FRkqxMfMlvqaEQv6hgiLoJXmeFBFMA6Uw-kcECgRXs_VzE6QVNPMRTrh402Z9Rn1dUVC_2B3WwopG_KNcftFARDQZD0K-a7swHAb_jftghftWtzrTqa8GTKMKuLCHS6ZJooPXOGpndn1h2yYO7bIF4GiPE80HgaLrgZDAJ-bf71LXhWmvmPtPiU0UGZeH1Zp4945yS5PHK1WVCMPoIR2XVqv9d9k08ZKqQPtnNOS1YsvdZOaY1Jy76eFIhCMFr1yhR0GyBmtVs6_wf9yEdi-SXSjqiciD77bk9pKf2p4b8C_9jhY3SJvB9wgLGUbDS0Y3gFG63EHcMKva4FVHFiov-7_abNk3i3RIQGSQOIFfRj3zZaSVngR8PcRoUa9z0FhpaicLUkREG-VRpE_wUZhE",
"results" : [
{
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/generic_recreational-71.png",
"name" : "Park Leśny Zdroje",
"photos" : [
{
"height" : 3024,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/103847965103971799822\"\u003eKSD\u003c/a\u003e"
],
"photo_reference" : "CmRaAAAAHvmblqXHuIBST9cZZI3yLtIuay_of90rDBUOoBQ64Luh7U_bVFTK5jhliXE9pFhRWMZjw4yHJXOFbxKQYBmEJwvBLNXkQGZrr5CvjlPT0HBHKququkGzjA8JJvbIdVC4EhCX_9SFH1F88ezn0N9XUaEfGhQpUDqAXZzLaSn0rrIIdMFwjCz6yA",
"width" : 4032
}
],
},
]
And i cannot somehow access photo_reference from array photos.
{parks.results.map((element,index)=>
<View key={index} style={AppStyle.mapCard}>
<View style={AppStyle.mapCardImg}>
//Tried this
<Text>{element.photos.map(item => item.photo_reference)}</Text>
//and this
<Text> {element.photos.photo_reference} </Text>
</View>
<View style={AppStyle.mapCardDescription}>
<Text>{element.name}</Text>
<Text>
({element.rating})
</Text>
</View>
</View>
</View>
)}
I know it's array in array and i need to iterate through it but it doesnt work.
This way: {element.photos.map(item => item.photo_reference)} i have undefined is not an object(evaluating element.photos.map)
This way {element.photos.photo_reference} undefined is not an object
Whats the solution in react Native?
Google Maps Api is not always returning every property of single Place. Error was that some places doesn't have photos so there's no array in json. The same about rating and others.
Adding conditions to check if variable exists solves problem.
element.photos && element.photos.map(item => item.photo_reference)

React native list Each child in a list should have a unique "key" prop

I am simply trying to do a venues list.
Here is the result of console.log(this.state.venues):
Array [
Object {
"key": "5b0ac89e***",
"venuename": "Venue1",
},
Object {
"key": "557d70asd****",
"venuename": "Venue2",
},
Object {
"key": "58f316ccsa****",
"venuename": "Venue3",
},
]
I am creating this data by pulling it from fq-api like this:
for (var i=0; i < 5; i++) {
this.state.venues.push({
venuename: response.data.response.groups[0].items[i].venue.name,
key: response.data.response.groups[0].items[i].venue.id
});
}
And here is my JSX:
<View style={styles.list}>
<FlatList data={[this.state.venues]}
renderItem={({item}) => <Text style={styles.item}>{item.venuename}</Text>}
keyExtractor={(item, index) => item.key} />
</View>
I am receiving Each child in a list should have a unique "key" prop Error. Everything seems ok to me, I don't understand why it fails. I don't know what is this "key prop", I have it from fetch and tried to use it but I can't proceed.
Thanks for your help.
Your error is in your data prop.
You're putting a bi-dimensional array to the data prop, so the keyExtractor will try to extract: [].key (undefined) instead item.key...
I think you're also rendering only one item on the list because of the bidimensional array, I'm correct?

How to access a local image using a local image url in a json file in react native?

I have problem in accessing the local image url in a json file. The images are stored in image directory. I have got some image addresses stored in a JSON array like this :
jsonResponse=
[ {"id": "1", "myImage": "./image/img1.png", "myText": "Anytext"},
…
]
const first = jsonResponse[0]
But when I try calling that using first.myImage in Image, it doesn't work; I'm able to get everything else. So, I try calling it like:
source={require('{first.myImage}')} as well as source={require({first.myImage})}
But it says, invalid prop type. I am able to access all other elements. I have also updated the JSON as:
[ {"id": "1", "myImage": "require('./image/img1.png')", "myText": "Anytext"},
…
]
source={first.myImage} OR source={{first.myImage}}
but that gives the same error too. Please help me.
makesure you are accessing the image in the same directory where image resides or else navigate to the image with proper path
I'm assuming you are able to retrieve the filepath from the json file and that the path is correct. Based on that, try using:
jsonResponse = [{"id": "1", "myImage": "./image/img1.png", "myText": "Anytext"}, ...]
Then on your app create two const to hold your variables. The first one you'll use to save the path you retrieve from the json. The second will be the one you'll use as source of your Image component.
constructor() {
const imagePath = first.myImage;
const image = require(imagePath);
}
...
<Image
source={image}
style={{ height: 30, width: 30, resizeMode: 'contain' }}
/>
...
Alternatively, you can also try importing the image this way:
import image from first.myImage;
JSON File:
{
"id": 2,
"name": "Toyota Corolla XLI\\Hatchback Automatic",
"details": "4 seater, diesel",
"picture": "./static/images/XLI.jpg",
"overcharge": "PKR 179 per excess km",
"weekday": "PKR 190/hr",
"weekend": "PKR 287/hr"
},
And then add inyour .js file like this:
{PostData.map((postDetail, index) => {
return (
<Link href="details">
<Card className="carditem">
<Card.Body style={{ cursor: "pointer" }}>
<Row>
<Col xs="12" sm="4">
<img
src={postDetail.picture}
class="d-block"
height="170"
/>

Deep level JSON Object referencing

I have searched and reviewed similar posts on this subject but no luck. I have valid JSON data returned to my app from my firebase Database but unable to reference the elements beyond first level. I need to pull the elements (url link) of the photos array object that is also an object of gallery array object. When i use the code snippet below I get the red screen listing all of the JSON object in the gallery object.
<TouchableOpacity >
<Image
source={{ uri: gallery }}
style={styles.roundedNavImageStyle}
/>
</TouchableOpacity>
When I change the source to reference what I need given the screenshot, I get errors "Cannot read property of [0] of undefined or Cannot read property photos of undefined.
<TouchableOpacity >
<Image
source={{ uri: gallery[0].photos }}
style={styles.roundedNavImageStyle}
/>
</TouchableOpacity>
Please help me. The photo links are the only elements of my JSON data I am unable to access which I need badly. I am able to access the image elements and other textual elements. I have also tried to simplify my JSON by removing the gallery node and starting with a photos node but getting the same issues. Thanks for your anticipated help. Please use my case rather than a generic json object to help me quicker.
Here's a snipet of my JSON object as stored in Firebase backend.
"places": [{
"id": "a",
"image": "https://res.cloudinary.com/obisi7/image/upload/v1537575323/tourNaija/slave/slavePic.jpg",
"title": "Slave Trade Museum",
"description": "Excerpts from Freeman Institute",
"subTitle": "One of many rare gems of history and education",
"phone": "",
"credit": "The Freeman Institute",
"gallery": [{
"id": "v1",
"photos": [{
"id": "p1",
"pic1": "https://res.cloudinary.com/obisi7/image/upload/v1537575322/tourNaija/slave/abolitionCannon.jpg",
"pic2": "https://res.cloudinary.com/obisi7/image/upload/v1537575322/tourNaija/slave/holdingCell.jpg",
"pic3": "https://res.cloudinary.com/obisi7/image/upload/v1537575322/tourNaija/slave/slaveMarket.jpg",
"pic4": "https://res.cloudinary.com/obisi7/image/upload/v1537575323/tourNaija/slave/slaveNoReturn.jpg",
"pic5": "https://res.cloudinary.com/obisi7/image/upload/v1537575323/tourNaija/slave/bibleAtBadagry.jpg",
"pic6": "https://res.cloudinary.com/obisi7/image/upload/v1537575322/tourNaija/slave/bridge.jpg"
}]
}]
},

Resources