Reputation: 153
I need to use different wrappers to render the screen based on a certain condition. Example, I have a situation where I need to wrap the content in a view
<View>
<Text> </Text>
<View> </View>
{ and other elements here }
</View>
But in a different scenario, I need the View to be Content from nativeBase. if useContent variable is true, then render everything using Content as a wrapper, else use View. How would I best do that ?
Upvotes: 2
Views: 873
Reputation: 968
Use a ternary operator to help you conditionally render.
render() {
const useContent = true;
return useContent ? (
<Content>
<Text></Text>
<View></View>
</Content>
) : (
<View>
<Text></Text>
<View></View>
</View>
)
}
It may also be better to extract these two pieces into their own components. Just so your component file doesn't become too large and maintainability starts to be a concern. Edit: If you want to keep the children of the component the same and just the wrapping element to change create a second component that renders children:
class WrappingElement extends Component {
render() {
const { children, useContent } = this.props;
return useContent ? (
<Content>{children}</Content>
) : (
<View>{children}</View>
)
}
}
class Foo extends Component {
render() {
<WrappingElement useContent={false}>
<Text>Hello World!</Text>
<View></View>
</WrappingElement>
}
}
Upvotes: 1
Reputation: 3150
<View>
{condition == true ?
(
<Text> </Text>
<View> </View>
)
:
(
{ and other elements here }
)
}
</View>
Upvotes: 1
Reputation: 16277
<View>
booleanCondition1() && <Text> </Text>
booleanCondition2() && <View> </View>
booleanConditionN() && { and other elements here }
</View>
Upvotes: 0