Minimum width/height in React Native

This answer is outdated now, use halilb's answer.

I solved this by using the onLayout prop, its very easy:

Example:

Step 1: I create a prop in our state that will be holding the current height of the image called curImgHeight.

constructor(){
  super(props);
  this.state={curImgHeight:0}
}

Step 2: Use the prop in any View or Element that supports the onLayout prop.

Here I use it with an Image. Then all we have to do is, change that state property whenever the actual image height is than our minimum height.

render(){
  <Image
    source={{uri: "https://placehold.it/350x150"}}
    resizeMode='cover'

    style={[styles.image, {height:(this.state.curImgHeight<=0?null:this.state.curImgHeight)}]}

    onLayout={(e)=>{
      let {height} = e.nativeEvent.layout;
      let minimumImgHeight = 400; //We set the minimum height we want here.
      if(height<= minimumImgHeight){ //Whenever the real height of the image is less than the minimum height
        this.setState({curImgHeight:minimumImgHeight}); //just change the curImgHeight state property to the minimum height.
      }
    }}
  />
}

Thats how I solved it for me.

p.s: During my search I found that react-native unofficially supports minHeight and maxHeight but only for iOS and not for Android. I wouldn't dare using them though. The above code works well and gives me control.


minHeight, maxHeight, minWidth and maxWidth properties are supported as of react-native version 0.29.0 for iOS and Android.

Here is the maxHeight description from react-native documentation. This description also applies for other min/max style properties.

maxHeight is the maximum height for this component, in logical pixels.

It works similarly to max-height in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See https://developer.mozilla.org/en-US/docs/Web/CSS/max-height for more details.

A dummy example:

<View
  style={{
    minWidth: '20%',
    maxWidth: 500,
    minHeight: '10%',
    maxHeight: 150,
  }}
/>

I was able to work out the solution for you. Here's a working demo... https://rnplay.org/apps/vaD1iA

And here are the key parts.

First, you pull in the device dimensions...

var Dimensions = require('Dimensions');
var {
  width,
  height
} = Dimensions.get('window');

Here's the button component, which uses the device width as the basis for the button's with

const Button = React.createClass({
  render(){
    return(
      <TouchableHighlight>
        <Text style={[styles.button,{width: width - 20}]}>
          {this.props.children}
        </Text>
      </TouchableHighlight>
    )
  }
});

Then, as you can see here, the button width will be the same regardless of label content width.

enter image description here

Tags:

React Native