Bagusflyer
Bagusflyer

Reputation: 12925

How to vertically aligned my image to top in my React-native component

I'd like to top aligned my image in React-native. But don't know what to do. Here is my layout and its style:

class layout extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.toolbar}>
          <Text style={styles.left}>
            Left Button
          </Text>
          <Text style={styles.title}>
            This is my title
          </Text>
          <Text style={styles.right}>
            Right Button
          </Text>
        </View>
        <View style={styles.content}>
          <Image style={styles.image}
            source={require('./back.jpg')}
            resizeMode="contain"
          ></Image>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  toolbar: {
    backgroundColor: '#B5AC3a',
    height:64,
    flexDirection:'row'
  },
  left: {
    marginTop:30,
    fontSize: 14,
    textAlign: 'center'
  },
  right: {
    marginTop:30,
    fontSize: 14,
    textAlign: 'center'
  },
  title: {
    marginTop:30,
    flex: 1,
    fontSize: 14,
    textAlign: 'center'
  },
  content: {
    backgroundColor:'#ffecff'
  },
  image: {
    width: Dimensions.get('window').width - 20,
    margin: 10,
    alignSelf:'center'
  }
});

Here is the result:

enter image description here

Apparently there are a lot of space between my image to top of my screen. I tried: flex-start. But doesn't work. What should I do? Thanks.

P.S: It's fine if I use View instead of Image like this:

class layout extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.toolbar}>
          <Text style={styles.left}>
            Left Button
          </Text>
          <Text style={styles.title}>
            This is my title
          </Text>
          <Text style={styles.right}>
            Right Button
          </Text>
        </View>
        <View style={styles.content}>
          <View style={styles.messageBox}>
           <Text>This is line one</Text>
           <Text>This is line two</Text>
          </View>
        </View>
      </View>
    );
  }
}

Result:

enter image description here

Upvotes: 3

Views: 5421

Answers (1)

Thanh-Quy Nguyen
Thanh-Quy Nguyen

Reputation: 3275

Your resizeMode='contain' on your image is conflicting with the dimensions you want to define in styles.image.
Simply remove resizeMode='contain' in your <Image> properties and it should work.

Something else: I would strongly advise you, depending on what you're trying to do, to use a ScrollView instead of the simple View when you have extendable content (namely anything that isn't completely static). This seems to be what you need.

Upvotes: 3

Related Questions