{{announcement.body}}
{{announcement.title}}

Custom Container Component in React Native With Different Content and Style

DZone 's Guide to

Custom Container Component in React Native With Different Content and Style

In this article, we discuss how to create custom container component in React Native with different content and styling.

· Web Dev Zone ·
Free Resource

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." 

JavaScript


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. 

JavaScript


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.

JavaScript




x
3


 
1
{props.children}        
8
    boxContainer:{



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 spread operator in JavaScript.

JavaScript




x
1


1
{...styles.boxContainer, ...props.style}
5
const BoxContainer = props => {



With the help of the spread operator, the style values of boxContainer and style are combined and passed up as a new list. 

JavaScript


Now, our custom container component is ready to be used. Let's use it with different content and style and see the result.

JavaScript



And the result:

Final output

Further Reading

Topics:
web dev ,react ,javascript ,angular ,vue ,spa ,custom component

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}