Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  49] [ 2]  / answers: 1 / hits: 6939  / 4 Years ago, mon, march 16, 2020, 12:00:00

I'm creating a simple custom component that will set dynamic height and width within text.



Class CustomComponent extends React.Component{
render(){
if(this.props.children){
if(this.state.isLoading){
console.log(this.props.children)

//Here i want to know what JSX is passing

return(
<View>
<ActivityIndicator size={'large'}/>
</View>
)
}
return(
<ImageBackground
source={this.props.source}
>
{this.props.children}
</ImageBackground>
)
} else if(this.state.isLoading){
return(
<View>
<ActivityIndicator size={'large'}/>
</View>
)
} else return(
<Image
source={this.props.source}
/>
)
}
}


//Use with text
<CustomComponent>
<View>
<Image {passing image} />
<Text>Sample</Text>
</View>
</CustomComponent>


But now i need to handle if the children only passing <Images/> with <Text> or not, any suggestion?


More From » reactjs

 Answers
1

If there are multiple elements, the children passed by props is actually an array,



children:  

[0]: <Image {passing image} />
[1]: <Text>Sample</Text>


If you arrange the child elements like below and the structure is fixed.



  <View>
<Image {passing image} />
<Text>Sample</Text>
</View>


You can visit the children array of the children via (with optional chaining perhaps)



this.props.children.props.children[1].type === 'Text'


which means in your situation, you can check the length of it, or whether the second element's type fit Text, to find out if the Text component is been passed or not.



Try it online:



Edit






Update



If we want the full view of the children, console without the attribute type would be good.



this.props.children.props.children[1]


type: div
key: null
ref: null
props: Object
_owner: FiberNode
_store: Object

[#4477] Thursday, March 12, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dusty

Total Points: 739
Total Questions: 97
Total Answers: 85

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;