Categories
JavaScript Answers React Native Answers

How to set up a table layout in React Native?

Spread the love

Sometimes, we want to set up a table layout in React Native.

In this article, we’ll look at how to set up a table layout in React Native.

How to set up a table layout in React Native?

To set up a table layout in React Native, we can nest views.

For instance, we write:

import * as React from 'react';
import { View, Text } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

const renderRow = (item) => {
  return (
    <View
      style={{ flex: 1, alignSelf: 'stretch', flexDirection: 'row' }}
      key={item}>
      <View style={{ flex: 1, alignSelf: 'stretch' }}>
        <Text>{item}</Text>
      </View>
      <View style={{ flex: 1, alignSelf: 'stretch' }}>
        <Text>{item}</Text>
      </View>
      <View style={{ flex: 1, alignSelf: 'stretch' }}>
        <Text>{item}</Text>
      </View>
    </View>
  );
};

export default function App() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      {Array(5)
        .fill()
        .map((_, i) => {
          return renderRow(i);
        })}
    </View>
  );
}

to create the renderRow function that renders a View with Views inside.

We make them display side by side by setting flexDirection to 'row'.

And we make the outer View span the width of the outermost View by setting alignSelf to 'stretch' and flex to 1.

Finally, we call renderRow in the map callback to render the nested Views in renderRow.

Conclusion

To set up a table layout in React Native, we can nest views.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *