I am learning React Native and want to build an app (Android and IOS) that will build the components within the main View when the page loads, pulling the data for each component from a JSON file.
Eg the JSON for that page might have 3 text items and an image, and the load would then build those components and they would display on the page.
Would that be possible and if so, how where should I put the code to do this - eg Hooks, useEffect() within the View component? Woud that be an issue as I believe useEffect would be called twice - once before the new components are added and then again after.
Also, ideally, the components might be embedded - eg a component with another one embedded for different styling, or for a link eg
<Text style={mainStyles.heading}>a test <Text style={mainStyles.p}>embedded</Text> text component</Text>
or
<Text style={mainStyles.heading}>a URL link <Text style={mainStyles.p} onPress={() => Linking.openURL("https://www.microsoft.com")}> Microsoft</Text> text component</Text>
Finally, when navigating between pages, it would need to have some way of passing a value to the incoming page so it knows which JSON to import (ie in web terms, a query string, cookie or local storage value)
Would this be possible?
CodePudding user response:
Dynamic components
You can use <FlatList>
. This will take a list of things, and create a "component" as you put it for each item in that list.
So, if you have a list of items, and each "item" has 4 properties, like: item = { text1, text2, text3, pic }
Then your FlatList could look like this:
<FlatList
data={exampleList}
keyExtractor={({ item, index }) => index}
renderItem={({ item, index }) => (
<View>
<Text>{item.text1}</Text>
<Text>{item.text2}</Text>
<Text>{item.text3}</Text>
<Image source={item.pic} />
</View>
)}
/>
So, you could parse multiple of your JSON-files into a List of these "items" (assuming they all have 3 texts and 1 picture).
And yes, you can add onPress to the <View>
, or whatever you need.
Passing values into the next screen
So, examples with HTTP-addresses, you can often add GET-data, just like you mentioned.
However, you often want to send data to your own screens. In that case, you need to have some navigation in place. So, if you currently can switch screens via navigate(), you could pass additional parameters. These would be accessible in the second screen via; props.route.params
So, navigate("LoadJSONPage","test42.json")
and in the "LoadJSONPage", you can access the parameter "test42.json" via props.route.params
. You can of course send multiple parameters, but you will have to specify index when accessing; props.route.params[0]
would be "test42.json"