Kingsley Ubah 21. Web Developer. Technical Writer. African in Tech.

Using methods like zIndex in React Native to stack elements

5 min read 1469

Using Methods Like Zindex In React Native To Stack Elements

React Native is a popular technology used to develop Android and iOS applications. Although it is built on React — Facebook’s JavaScript toolkit for creating user interfaces — React Native targets mobile platforms as opposed to browsers.

With React Native, you get the benefit of being able to use the same technologies you’d use in web development like CSS and JavaScript. React Native also provides a ton of elements for you to compose your mobile app’s UI.

When building out your UI, it can be easy for two or more React Native elements to overlap each other. In other words, the elements are stacked on one another. When this happens, you may not like the order in which they appear on the screen.

You can use CSS parameters like position and zIndex in React Native to manage the order in which overlapping components are stacked. This tutorial will explore these and other techniques and best practices for stacking elements.

We will cover:

To follow this tutorial, you’ll need basic knowledge of React Native, some familiarity with CSS, and a starter app on Expo Snack.

Stacking in React Native with the CSS position property

The CSS position property is used to position an element on a page either in relation to its normal position or in absolute terms. In other words, it positions the element relative to its nearest positioned ancestor.

After applying the position attribute to an element, you’ll then use the top, bottom, left, and right attributes to specify exactly where you want the element to be placed.

In this section, we’ll use three <View> elements, along with a bit of CSS, to create three overlapping containers in our app.

By this point, you should have your starter app at Expo Snack already set up. If so, replace the following App component with the default one found inside the App.js file in your project:

export default function App() {
  return (
    <View style={styles.container} >
      <View style={[styles.square, {backgroundColor: 'green'}]} />
      <View style={[styles.square, {backgroundColor: 'red'}]} />
      <View style={[styles.square, {backgroundColor: 'blue'}]} />
    </View>
  );
}

Here we’re placing three <View> elements with different background colors inside a container <View> element.

Next, inside the same file, replace the default styles code with the following styles:

const styles = StyleSheet.create({
  container: {
    margin: 20,
    marginTop: 30,
    flex: 1,
    flexDirection:'row',
    backgroundColor: 'linen',    
  },
  square: {
    height: 70,
    width: 70,        
  },
});

With the above code, your three nested <View> elements are styled into squares and aligned properly in the parent container. The output is as follows:

Three Square View Elements, Green, Red, And Blue, Aligned In A Horizontal Row At Top Left Of Linen Colored Parent Container

In the above image, the elements are aligned horizontally and are clearly separate from each other. But say, for example, you want the green container at the bottom instead of at the top. You can use the CSS position property to reposition the green container.

Let’s see that in action. In the App.js file, add the position: 'absolute' property on the green container’s <View> element and set both bottom and right properties to 0 as the code below shows:

return (
    <View style={styles.container} >
      <View style={       
        [
          styles.square, 
          {backgroundColor: 'green', position: 'absolute', bottom: 0, right: 0}
        ]
        } 
      />
      <View style={[styles.square, {backgroundColor: 'red'}]} />
      <View style={[styles.square, {backgroundColor: 'blue'}]} />
    </View>
  );

With this code, the first container will be placed at the bottom right corner of the screen, which we set using bottom: 0, right: 0. This gives us the following output:

Same Three Square Elements And Parent Container As In Previous Image, But First Green Square Is Now At Bottom Right Of Parent Container While Red And Blue Squares Now Occupy First And Second Positions At Top Left Of Parent Container

Notice how the second container now occupies the position of first, while the third container occupies the second position. This is because position: 'absolute' completely removed the element from the normal flow.

Let’s now make all three containers overlap. Update the style property on all nested <View > elements to the following:

return (
    <View style={styles.container} >
      <View style={[styles.square, {backgroundColor: 'green', position: 'absolute', top: 0, left: 0}]}/>
      <View style={[styles.square, {backgroundColor: 'red', position: 'absolute', top: 30, left: 30}]}/>
      <View style={[styles.square, {backgroundColor: 'blue', position: 'absolute', top: 60, left: 60}]} />
    </View>
  );

Here we’re offsetting the red square 30px from the top and 30px from the left, and the third box 60px from the top and 60px from the left. The result is shown in the image below:

Same Three Square Elements And Linen Colored Parent Container As In Previous Images, But Now Overlapping And Offset So That Red Square Overlaps Bottom Right Corner Of Green Square And Blue Square Overlaps Bottom Right Corner Of Red Square

In the image above, you can see that all three boxes have overlapped and that the blue box is placed in front of the other two, as it has the highest priority. But what if you wanted to bring the red box to the front instead?



The answer is to set its zIndex value.

Using zIndex in React Native to stack and reposition elements

When two or more React Native elements overlap, their zIndex values will determine where they’ll be placed in the stack. The element with the highest zIndex will be placed in front, while the element with the lowest zIndex will be placed at the back.

By default, the zIndex value in React Native increases from top to bottom. Going back to the image of the three overlapping squares, this default behavior makes it obvious that the blue square has the highest zIndex value while the green has the lowest.

To place the red square in front, all you have to do is set its zIndex to an integer value greater than or equal to 1.

// <View />
<View style={[styles.square, {backgroundColor: 'red', position: 'absolute', top: 30, left: 30, zIndex: 1}]}/>
// <View />

Here’s the result:

Same Three Square Elements And Linen Colored Parent Container As In Previous Images, Still Offset As In Last Image, But Now With Red Square In Front Of Both Other Squares

To place another square in front of the red one, set a higher zIndex value on the style property of that element.

So far we have demonstrated how to stack elements using CSS position and zIndex properties in React Native. In React Native, the FlatList element provides a modern way to stack elements.

Stacking React Native elements with FlatList

React Native provides a FlatList element that allows you to place elements on a screen using a grid layout. In this section, we’ll demonstrate how to stack elements using FlatList by enhancing the elements we created in the last section.

Let’s add a simple FlatList element in our App.js file. At the top of the file, import FlatList from react-native:

import { FlatList, ... } from 'react-native';

Next, just above the App component, create a bgColorArr array with several colors. Then, create a function named renderItem and return a <View> element from it:

const bgColorArr = [
  'green',
  'red',
  'blue',
  'yellow',
  'black',
  'orange'
]

function renderItem({item}) {
  return (    
      <View style={[styles.square, {backgroundColor: item}]}/>          
  );
}

Next, modify the App component. Replace all four <View> elements inside the return statement with a single FlatList:

return (
    <FlatList data={bgColorArr} renderItem={renderItem} />
  );

Here we passed the following:

  • bgColorArr: the array of items (background colors) that we want to iterate over
  • renderItem: the component that we want to render for each item (i.e. for each color)

As a result, the FlatList will render six View elements with different background colours:

Six Squares Stacked In Vertical Column At Left Side Of White Parent Container, In Order From Top To Bottom: Green, Red, Blue, Yellow, Black, Orange

Here the items are rendered into a row, but you can specify columns as well. Let’s see how.

Rendering items into columns with FlatList

In this section, we’ll render the items into a grid system with three columns.


More great articles from LogRocket:


Modify the App component once again. Add two attributes — numColumn and key — and set their values to 3:

return (
    <FlatList 
      data={bgColorArr} 
      renderItem={renderItem}
      numColumns={3}
      key={3} 
    />
  );

The output is as follows:

Same Six Square Elements As In Previous Image Now Arranged In A Grid Of Two Rows And Three Columns. First Row From Left To Right Contains Green, Red, And Blue Squares. Second Row From Left To Right Contains Yellow, Black, And Orange Squares.

Using React Native’s Dimension API to create responsive columns

To make sure that the items are aligned well across different screen resolutions, use the Dimension API provided by React Native to get the width and height depending on the device.

In the App.js file, get the width of the screen and divide it by the number of columns to get the size of each column. Then, pass that value to the width property of your render item:

const screenWidth = Dimensions.get("windows").width;
const numColumns = 4
const tileSize = screenWidth / numColumns

function renderItem({item}) {
  return (    
      <View style={[styles.square, {backgroundColor: item, width: tileSize, height: tileSize }]}/>          
  );
}

This code ensures that you accurately use the available spacing at all times. Don’t forget to import Dimension from react-native at the top of the file for the code to work.

Conclusion

I hope this tutorial helped you understand stacking better. You should now be able to create flexible grid systems in your React Native app using the techniques we covered in this post — zIndex, position, and Flatlist.

If you have any questions regarding this topic, leave a comment and I’ll respond as soon as I get it. Have a great week!

LogRocket: Instantly recreate issues in your React Native apps.

LogRocket is a React Native monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your React Native apps.

LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket's product analytics features surface the reasons why users don't complete a particular flow or don't adopt a new feature.

Start proactively monitoring your React Native apps — .

Kingsley Ubah 21. Web Developer. Technical Writer. African in Tech.

Leave a Reply