kingkong
kingkong

Reputation: 263

Flex box dynamic width and height

I am trying to create a messages view using react-native e.g.:

enter image description here

As you can see:

  1. The bubbles have a dynamic width and height based on the content
  2. There is a maximum width for the bubbles and they grow downwards

I am trying to recreate this using react native, however I am only able to acheive (2) and not sure how to go about acheiving both.. this is what i have thus far:

enter image description here

  <View style={{flex:1,backgroundColor:'blue',flexDirection:'row'}}>
     <View style={{backgroundColor:'orange'}}>
            <View style={{width:90,flex:1}}>
              <Text>123</Text>
              </View>
     </View>
     <View style={{flex:0.25,backgroundColor:'red'}}>
              <Text>123</Text>
     </View>
  </View>

If I increase the orange view to represent a big bubble then it just goes off the screen... e.g.:

enter image description here

Upvotes: 16

Views: 20311

Answers (4)

vin
vin

Reputation: 346

I was having same issue. I tried many things including putting wrappers here-and-there (like mentioned in previous answers). None of them worked.

@André Junges's answer is not correct because @kingkong and I have different requirements.

Then, I saw that flex can also take value -1. And setting it solved the problem.

Here is the code:

const messages = [
              'hello',
              'this is supposed to be a bit of a long line.',
              'bye'
              ];
return (
  <View style={{
            position: 'absolute',
            top: 0,
            left: 0,
            width: 150,
            alignItems: 'flex-end',
            justifyContent: 'flex-start',
            backgroundColor: '#fff',
            }}>

{messages.map( (message, index) => (
  <View key={index} style={{
                  flexDirection: 'row',
                  marginTop: 10
                }}>
    <View style={{
                  flex: -1,
                  marginLeft: 5,
                  marginRight: 5,
                  backgroundColor: '#CCC',
                  borderRadius: 10,
                  padding: 5,
                }}>
      <Text style={{
                    fontSize: 12,
                    }}>
        {message}
      </Text>
    </View>
    <Image source={require('some_path')} style={{width:30,height:30}} />
   </View> 
  ))} 
 </View>
)

And here is the result:

And here is the result:

Upvotes: 15

Andr&#233; Junges
Andr&#233; Junges

Reputation: 5347

I know this question is from a year ago, but I had a similar issue and I think it can be useful for other devs.

So what I was trying to achieve was to create boxes like the image below where I would have a text in the left, and an arrow in the right.
Note that the boxes should have a auto height - since the text can be multiple lines..

enter image description here

JSX

<View style={styles.container}>
  <View style={styles.textContainer}>
    <Text style={styles.text}>{props.message.text}</Text>
  </View>
  <View style={styles.iconContainer}>
    <Icon name="chevron-right" size={30} color="#999" />
  </View>
</View>

Styles

container: {
  flex: 1,
  flexDirection: 'row',
  alignItems: 'center',
  backgroundColor: '#FFF',
  marginBottom: Metrics.baseMargin,
  borderRadius: 3,
},
textContainer: {
  flex: 1,
  flexDirection: 'column',
  paddingVertical: 30,
  paddingHorizontal: Metrics.doubleBaseMargin,
},
text: {
  color: '#333',
},
iconContainer: {
  width: 35,
  borderLeftWidth: 1,
  borderLeftColor: '#ddd',
  justifyContent: 'center',
  alignItems: 'center',
  alignSelf: 'stretch',
},

And of course, it didn't work. For some reason if I had an parent with flexDirection: 'row' the child wouldn't grow. The text was being wrapped in multiple lines, but the parent's height (.textContainer) wasn't growing - and the text was being displayed even outside the container in some cases. You can see it in the image below ( third message ).

enter image description here

The fix was to wrap this whole component with one more View, like the code below:

<View style={styles.wrapper}>
  <View style={styles.container}>
    <View style={styles.textContainer}>
      <Text style={styles.text}>{props.message.text}</Text>
    </View>
    <View style={styles.iconContainer}>
      <Icon name="chevron-right" size={30} color="#999" />
    </View>
  </View>
</View>

The .wrapper class has only styles details on it (moved from .container)

wrapper: {
  backgroundColor: '#FFF',
  marginBottom: Metrics.baseMargin,
  borderRadius: 3,
},

Upvotes: 2

Colin Ramsay
Colin Ramsay

Reputation: 16466

I've come up with a somewhat contrived way of doing this. Let's look at the problem first.

We can use flexbox to put the "badge" on the left and the text on the right, then have "message rows" going down horizontally. That's easy, but what we want is for the message row to change width depending on its content, and flexbox won't let you do that as it greedily expands to fill all of the space.

What we need is a way of checking the width of the message text then resizing the view accordingly, forcing it to a specified width. We can't use measure to get the text width since that actually only gives us the width of the underlying node, not the actual text itself.

To do this I stole an idea from here and created a bridge to Obj-C which creates a UILabel with the text and gets its width that way.

//  TextMeasurer.h
#import "RCTBridgeModule.h"
#import <UIKit/UIKit.h>

@interface TextMeasurer : NSObject<RCTBridgeModule>

@end


//  TextMeasurer.m
#import "TextMeasurer.h"

@implementation TextMeasurer

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(get:(NSString *)text cb:(RCTResponseSenderBlock)callback)
{
  UILabel *label = [[UILabel alloc]init];
  label.font = [UIFont fontWithName:@"Helvetica" size:14.0];
  label.text = text;

  callback(@[[NSNumber numberWithDouble: label.intrinsicContentSize.width]]);
}

@end

I then wrapped the usage of this into a component:

var AutosizingText = React.createClass({
    getInitialState: function() {
        return {
            width: null
        }
    },

    componentDidMount() {
        setTimeout(() => {
            this.refs.view.measure((x, y, width, height) => {
                TextMeasurer.get(this.props.children, len => {
                    if(len < width) {
                        this.setState({
                            width: len
                        });
                    }
                })
            });
        });
    },

    render() {
        return <View ref="view" style={{backgroundColor: 'red', width: this.state.width}}><Text ref="text">{this.props.children}</Text></View>
    }
});

All this will do is resize the containing view if the width of the text is less than the original width of the view - which will have been set by flexbox. The rest of the app looks like this:

var messages = React.createClass({
    render: function() {
        var rows = [
            'Message Text',
            'Message Text with lots of content ',
            'Message Text with lots of content put in here ok yeah? Keep on talking bla bla bla whatever is needed to stretch this message body out.',
            'Keep on talking bla bla bla whatever is needed to stretch this message body out.'
        ].map((text, idx) => {
            return <View style={styles.messageRow}>
                <View style={styles.badge}><Text>Me</Text></View>
                <View style={styles.messageOuter}><AutosizingText>{text}</AutosizingText></View>
            </View>
        });

        return (
            <View style={styles.container}>
                {rows}
            </View>
        );
    }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignItems: 'stretch',
    flexDirection: 'column',
    backgroundColor: '#F5FCFF',
  },
  messageRow: {
    flexDirection: 'row',
    margin: 10
  },
  badge: {
    backgroundColor: '#eee',
    width: 80, height: 50
  },
  messageOuter: {
    flex: 1,
    marginLeft: 10
  },
  messageText: {
    backgroundColor: '#E0F6FF'
  }
});

AppRegistry.registerComponent('messages', () => messages);

And it gives you this:

enter image description here

I would keep an eye on the Github issue as this solution is definitely a bit clunky and at the very least I'd expect to see a better way of measuring text in RN at some point.

Upvotes: 4

iLoch
iLoch

Reputation: 769

So I think the strategy here is that you want to contain the message bubble inside a full width block, then have two inner views. One inner view attempts to be as thin as possible, that's the one you put text in. The other tries to be as wide as possible, thus condensing the other block just wide enough to contain the text.

<View style={{flex:1,backgroundColor:'blue',flexDirection:'row'}}>
  <View style={{flex:0,backgroundColor:'red'}}>
    <Text>123</Text>
  </View>
  <View style={{backgroundColor:'orange', flex: 1}}/> 
</View>

Upvotes: 1

Related Questions