cssreactjsreact-nativereact-native-imageimagebackground

React Native: how to make View inside ImageBackground have 100% width but with horizontal padding?


I have the following screen in my React Native app: enter image description here

The blue black and white background is an ImageBackground, and the green strip in the middle is a View. The code is:

<ImageBackground
  source={require('@images/login-background.jpg')}
  style={{
    flex: 1,
    width: '100%',
    resizeMode: 'cover',
    justifyContent: 'center',
  }}
>
  <View style={{
    width: '100%',
    backgroundColor: 'green',
    borderRadius: 15,
    padding: 15
  }}/>
  </ImageBackground>

I want there to be 15px of padding at the left and right edges of the green View. If the ImageBackground were a View I would've added 15px of padding to it, but when it's an ImageBackground that results in this:

enter image description here

Conversely, if I add margin: 15px to the green View, I get this:

enter image description here

How should I approach this, to make it look like this?

enter image description here


Solution

  • You can achieve the above requirement using Dimensions in React-Native

    import React from "react";
    import { ImageBackground, View, Dimensions } from "react-native";
    
    const screenWidth = Dimensions.get('window').width;
    
    export default App = () => (
        <ImageBackground
            source={{ uri: "https://reactjs.org/logo-og.png" }}
            style={{
                flex: 1,
                width: '100%',
                resizeMode: 'cover',
                justifyContent: 'center',
                alignItems: 'center'
            }}>
            <View style={{
                width: screenWidth - 30,
                backgroundColor: 'green',
                borderRadius: 15,
                padding: 15
            }} />
        </ImageBackground>
    );
    

    Hope this helps you. Feel free for doubts.