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 JSO
Here is another approach:-
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
const renderObject = {
type : "View",
children : [
{
type: "View",
styles: {
backgroundColor: "orange",
flex:1,
justifyContent:"center",
alignItems: "center"
},
children: [
{
type: "Text",
styles: {
color: "yellow",
fontSize: 20
},
text: "Hello"
},
{
type: "View",
styles: {
backgroundColor: "red",
width: 100,
height: 5,
marginTop: 10
},
children: []
}
]
},
{
type: "View",
styles: {
flex:1,
justifyContent:"center",
alignItems: "center"
},
children: [
{
type: "Text",
styles: {
color: "red",
fontSize: 40
},
text: "Hello"
}
]
},
{
type: "View",
styles: {
flex:1,
justifyContent:"center",
alignItems: "center",
backgroundColor: "green"
},
children: [
{
type: "Text",
styles: {
color: "white",
fontSize: 80
},
text: "Hello"
}
]
}
],
styles: {
flex:1
}
}
const CustomComp = (props) => {
const {type} = props;
if(type == "View"){
const {styles, children} = props;
return {children.map((item) => CustomComp(item))}
} else if(type == "Text") {
const {styles, text} = props;
return {text}
}
}
export default function App() {
return (
{CustomComp(renderObject)}
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
justifyContent: 'center',
},
});
You can find the full code on this Repo.