Is it possible to dynamically create and add view components in React Native? For example, firstly I have only empty screen and information of all views come from server in JSON, and then it is need to generate them on the screen. For example - application getting json from server. This json describes the screen that have to be builded:
{
"type": "linearlayout",
"subviews": [{
"type": "text",
"fields": {
"text": "This is text field"
},
"styles": {
"color": "",
"textSize": 14
}
}, {
"type": "button",
"fields": {
"text": "JUST BUTTON"
},
"transition": {
"name": "http://www.link.com"
}
}, {
"type": "text",
"fields": {
"text": "This is another text field"
},
"styles": {
"color": "",
"textSize": 18
}
}]
}
So, by that JSON I need dynamically views building in React Native. But I can't see any ability to write JS code inside JSX - only static views and dynamically changing of props
In React, dynamically importing a component is easy—you invoke React. lazy with the standard dynamic import syntax and specify a fallback UI. When the component renders for the first time, React will load that module and swap it in.
To render the components based on the component key in the JSON config, we first need to create an object that maps the components with the component key. As you can see, I have mapped the component key with the corresponding Reactstrap component. At the top, we will import all the required components.
Yes this is possible. Assume that you retrieve your JSON data successfully and save it to some state then in your render function you can use it like that;
render() {
var productList = [];
this.state.data.products.forEach(function (tmpProduct) {
productList.push(
<View style={cardView} key={tmpProduct.id}>
<Grid style={upperGrid}>
<Col style={{flex: 0.5}}>
<Thumbnail
source={require('../../../images/sample-image.png')}
style={itemThumb}>
</Col>
<Col>
<Text style={cardItemHeader} numberOfLines={2}>{tmpProduct.title}</Text>
<Text style={cardItemBody} numberOfLines={2}>{tmpProduct.description}</Text>
</Col>
</Grid>
</View>
);
}.bind(this));
return (
<Container theme={theme}>
<Image source={require('../../../images/grad-bg.png')} style={background} >
<Content style={scrollContent}>
{productList}
</Content>
</Image>
</Container>
)
}
I hope this code piece give you an idea. You can adapt it to your case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With