Lucas Anschau
Lucas Anschau

Reputation: 91

How to break line of multiple Text List Items when they exceeds it container size?

I am developing a react native app. In the app, I have a iterator mapping multiples types that are show inside a View. Each of these types have an specific color, so that is why I have an each tag for each type.

I have made a simplified example what I want and what is happening.

enter image description here

I want when the Text List Items exceeds its container, that they break to a new line. I tried many ways but don't discover how to do it.

The example: https://snack.expo.dev/@anschau/multiple-text-problem-not-breaking-line

The code:

import React from "react";
import { StyleSheet, Text, View } from "react-native";

const LabelTypes = [
  {
    styleType: "styleType1",
    label: "Extensive Type 1",
  },
  {
    styleType: "styleType2",
    label: "Another Extensive Type 2",
  },
  {
    styleType: "styleType3",
    label: "Type 3",
  },
  {
    styleType: "styleType4",
    label: "Type 4",
  },
  {
    styleType: "styleType5",
    label: "Type 5",
  },
  {
    styleType: "styleType6",
    label: "Type 6",
  },
];

const App = () => {
  
  return (
    <View style={[styles.container, {
      flexDirection: "row"
    }]}>
      {
        LabelTypes.map((item, index) => (
          <>
            { index > 0 && <Text> - </Text>}
            <Text style={[styles.label, styles[item.styleType] ]}>{item.label}</Text>
          </>
        ))
      }
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    maxWidth: "100%",
    marginTop: 50,
    marginLeft: 20,
    marginRight: 20,
    borderWidth: 1,
    borderColor: "gray"
  },
  label: {
    color: "black",
  },
  styleType1: {
    color: "blue"
  },
  styleType2: {
    color: "red"
  },
  styleType3: {
    color: "green"
  },
  styleType4: {
    color: "orange"
  },
  styleType5: {
    color: "coral"
  },
  styleType6: {
    color: "pink"
  },
});

export default App;

Upvotes: 1

Views: 288

Answers (1)

Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34790

Add to your container's (NOT individual labels') style:

flexWrap: 'wrap'

This will simply let items fill the container's width and fall into a new line when it doesn't fit.

Upvotes: 2

Related Questions