Patrick Adjei
Patrick Adjei

Reputation: 135

Is there a way to wrap background color around text in react-native?

Currently, this is what I am trying to avoid. As you can see the background color runs until the end of the width. It would be nice for the background color to surround the text.

enter image description here

I looked a tons of examples and I don't really see where they wrap background color around the text itself

<Text style={{backgroundColor:'blue'}}> TTeexxtt </Text>

I tried with flexWrap and it doesn't work just like so

<Text style={{backgroundColor:'blue', flexWrap:'wrap'}}> TTeexxtt </Text>

As always, thank you

Upvotes: 4

Views: 4868

Answers (1)

ajthyng
ajthyng

Reputation: 1275

two text lines with different sized pink and orange backgrounds behind them

Views in react native default to an alignItems prop of stretch. What does this mean though?

All children of your view will stretch to fill the width of their parent, with considerations for margin.

If you set the alignItems property of your parent view to something other than stretch, such as center, flex-start, or flex-end you will see the background color only extend around your actual text.

You can also use alignSelf on your Text views to adjust individual items.

Here is an example snack https://snack.expo.io/@ajthyng/vengeful-celery

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

const BGText = props => {
  const { background } = props;
  return <Text style={{backgroundColor: background, ...props.style}}>{props.children}</Text>;
}

export default class App extends React.Component {
  render() {
    return (
      <View style={{flex: 1, backgroundColor: 'white', alignItems: 'stretch', marginTop: 23}}>
        <BGText background='pink' style={{marginRight: 16}}>I am some text</BGText>
        <BGText background='orange' style={{alignSelf: 'flex-start', marginLeft: 16}} >My BG Color is short</BGText>
      </View>
    );
  }
}

Upvotes: 10

Related Questions