In React Native (and also in React) you can create custom components and use them easily as much as you want in your app. You may give custom styles and values to these components by passing different values in the props of these components. However, you can not change the child components of your custom components since they are already defined.
In some cases, you may want to have containers that look alike but also have different content and differ in style. At this point, custom container components come in.
Let’s create a custom container with the name, “BoxContainer.”
We want to add style to our container. The style we will give to our custom container component will be the common style in every usage of our component. So, let’s modify our code to return a view with some style.
You may also like:
React Native Developers: Create Your First App.
Since our component will be a container, it will contain different components when used. We need to pass these components to the container. This can be achieved with React’s “children” prop.
We also want to pass custom style to the container. As you know, this can be passed by
props.style. The problem here that must be handled is that we must combine the common style built in the component and the style passed to the component during usage. We must also allow the common style to be overwritten by the style passed during usage. We can achieve this with the
With the help of the
spread operator, the style values of
style are combined and passed up as a new list.
Now, our custom container component is ready to be used. Let’s use it with different content and style and see the result.
And the result: