Reputation: 6752
I want to create a wrapper component like this:
Wrapper Component:
class WrapperComponent extends Component {
render() {
return (
<Image source={someImage}>
<App />
</Image>);
}
}
App:
class App extends Component {
render() {
return (
<WrapperComponent>
<Text>Some text</Text>
</WrapperComponent>
}
}
I want to use this for the default things like a background image. Is there a way to do this? Sorry I am new in this language.
Upvotes: 12
Views: 18107
Reputation: 191976
You can create the wrapper using props.children
const WrapperComponent = ({ children }) => (
<Image source={someImage}>
{children}
</Image>
);
class WrapperComponent extends Component {
render() {
return (
<Image source={someImage}>
{this.props.children}
</Image>);
}
}
Whatever you'll put inside the <WrapperComponent></WrapperComponent>
tags will be rendered.
Upvotes: 32
Reputation: 3063
As per official docs 'Composition vs Inheritance' the Inheritance approach is not recommended. So, you can create AwesomeWrapper.js
with the content:
import React from 'react';
import { Image } from 'react-native';
export const AwesomeWrapper = (props) => {
return (
<Image source={props.imageSource}>
{props.children}
</Image>
);
}
and then use in your code like
<AwesomeWrapper imageSource="...">
...
</AwesomeWrapper>
Upvotes: 1