user7858768
user7858768

Reputation: 1026

ReactNative: How to have 2nd Text components share the line of 1 Text component spill over

In React Native is it possible for 2nd component to use the space that was partially used by 1st Text component spill over?

Example code:

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

export const TextProto = () => {

    return <View>

        <Text style={{borderWidth: 2, borderColor: 'green'}}>{'str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1'}</Text>
        <Text style={{borderWidth: 2, borderColor: 'green'}}>{'str-2 str-2'}</Text>
    </View>
};

Renders as:

enter image description here

Is it possible to render this as (preferably through styling settings):

enter image description here

Upvotes: 0

Views: 136

Answers (1)

Nostromo
Nostromo

Reputation: 1053

As @Uğur Eren stated, borders will not work for text components but you can achieve similar effect by using different background color for each word in your string or set of strings.

Below is a simple implementation for your case:

import React from "react";
import "./styles.css";
import { View, Text, StyleSheet } from "react-native";


const sentences = [
  {
    backgroundColor: "#cfa",
    color: "#000",
    sentence: "This is my first line that is very very long"
  },
  {
    backgroundColor: "#edf",
    color: "#000",
    sentence: "There it is a second one"
  },
  { backgroundColor: "#ecd", color: "#000", sentence: "Lorem ipsum veliyedin" }
];

export default function App() {
  return (
    <View style={styles.container}>
      {sentences.map(({ color, backgroundColor, sentence }) => {
        return sentence.split(" ").map((word) => {
          return (
            <Text style={[styles.text, { color, backgroundColor }]}>
              {word}
            </Text>
          );
        });
      })}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flexWrap: "wrap",
    flexDirection: "row",
    alignSelf: "flex-start"
  },
  sentence: {
    flexWrap: "wrap",
    flexDirection: "row",
    alignSelf: "flex-start"
  },
  text: {
    padding: 5,
    backgroundColor: "#eee"
    // margin:5
  }
});

CodeSandbox

Upvotes: 1

Related Questions