I was trying to check if the children (AssetExample2) of my parent (AssetExample) component have their own children. I would use this pattern for the splashscreen of the app that I’m building to hide when children have loaded but I can’t seem to make it work as the state hasChildren
that I created always returns false
what am I doing wrong here?
// App.js
import { Text, SafeAreaView, StyleSheet } from 'react-native';
import { Card } from 'react-native-paper';
import AssetExample from './components/AssetExample';
import AssetExample2 from './components/AssetExample2';
export default function App() {
return (
<SafeAreaView>
<Text>
I don't have children
</Text>
<Card>
<AssetExample>
<AssetExample2 />
</AssetExample>
</Card>
</SafeAreaView>
);
}
// AssetExample
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Image } from 'react-native';
export default function AssetExample({children}) {
const [hasChildren, setHasChildren] = useState(false);
useEffect(() => {
React.Children.forEach(children, (child) => {
if (!React.isValidElement(child)) {
if (child.props.children) {
setHasChildren(true);
}
}
});
}, [children]);
return (hasChildren &&
<View>
<Text>
I have children
</Text>
</View>
);
}
// AssetExample2
import { Text, View } from 'react-native';
export default function AssetExample2() {
return (<View><Text>I exist</Text></View>);
}