[javascript] How to use ImageBackground to set background image for screen in react-native

When I use in react-native it gives warning that using with children is deprecated and will be error in future. User instead.

So, If I use it doesn't give expected result which I was getting using

Here is the code I wrote for using

<ImageBackground source={require('../../img/splash/splash_bg.png')} style={styles.backgroundImage} >
        </ImageBackground>

And style code is

const styles = StyleSheet.create({
backgroundImage: {
    flex: 1,
    // width: undefined,
    // height: undefined,
    // flexDirection: 'column',
    // backgroundColor:'transparent',
    // justifyContent: 'flex-start',


},}

Expected result: getting when using <Image> Result using <ImageBackground>

This question is related to javascript react-native imagebackground

The answer is


i achieved this by:

import { ImageBackground } from 'react-native';

<ImageBackground style={ styles.imgBackground } 
                 resizeMode='cover' 
                 source={require('./Your/Path.png')}>

   //place your now nested component JSX code here

</ImageBackground>

And then the Styles:

imgBackground: {
        width: '100%',
        height: '100%',
        flex: 1 
},

     <ImageBackground
            source={require("../assests/background_image.jpg")}
            style={styles.container}

        >
            <View
                style={{
                    flex: 1,
                    justifyContent: "center",
                    alignItems: "center"
                }}
            >
                <Button
                    onPress={() => this.props.showImagePickerComponent(this.props.navigation)}
                    title="START"
                    color="#841584"
                    accessibilityLabel="Increase Count"
                />
            </View>
        </ImageBackground>

Please use this code for set background image in react native


I faced same problem with background image and its child components including logo images. After wasting few hours, I found the correct way to solve this problem. This is surely helped to you.

var {View, Text, Image, ImageBackground} = require('react-native');
import Images from '@assets';

export default class Welcome extends Component {
    render() {
        return (
            <ImageBackground source={Images.main_bg} style={styles.container}>
                <View style={styles.markWrap}>
                    <Image source={Images.main_logo} 
                    style={styles.mark} resizeMode="contain" />
                </View>
                <View style={[styles.wrapper]}>
                    {//Here put your other components}
                </View>              
                
            </ImageBackground>
        );
    }
}

var styles = StyleSheet.create({
    container:{
        flex: 1,
    },
    markWrap: {
        flex: 1,
        marginTop: 83,
        borderWidth:1, borderColor: "green"
      },
    mark: {
        width: null,
        height: null,
        flex: 1,
    },
    wrapper:{
        borderWidth:1, borderColor: "green",///for debug
        flex: 1,
        position:"relative",
    },
}

Logo on background Image

(PS: I put on the dummy image on this screen instead of real company logo.)


const { width, height } = Dimensions.get('window')


<View style={{marginBottom: 20}}>
   <Image 
        style={{ height: 200, width: width, position: 'absolute', resizeMode: 'cover' }}
        source={{ uri: 'https://picsum.photos/'+width+'/200/?random' }}
                />
   <View style={styles.productBar}>
       <View style={styles.productElement}>
            <Image
                  style={{ height: 160, width: width - 250, position: 'relative', resizeMode: 'cover' }}
                  source={{ uri: 'https://picsum.photos/'+ 250 +'/160/?random' }}
                        />
       </View>
       <View style={styles.productElement}>
             <Text style={{ fontSize: 16, paddingLeft: 20 }}>Baslik</Text>
             <Text style={{ fontSize: 12, paddingLeft: 20, color: "blue"}}>Alt Baslik</Text>
       </View>
   </View>
</View>



 productBar: {
    margin: 20,
    marginBottom: 0,
    justifyContent: "flex-start" , 
    flexDirection: "row"
  },
  productElement: {
    marginBottom: 0, 
 },

Screenshot


You can use "ImageBackground" component on React Native.

<ImageBackground
  source={yourSourceFile}
  style={{width: '100%', height: '100%'}}
> 
    <....yourContent...>
</ImageBackground>

Here is a link to the RN docs: https://facebook.github.io/react-native/docs/images

A common feature request from developers familiar with the web is background-image. To handle this use case, you can use the <ImageBackground> component, which has the same props as <Image>, and add whatever children to it you would like to layer on top of it.

You might not want to use <ImageBackground> in some cases, since the implementation is very simple. Refer to <ImageBackground>'s source code for more insight, and create your own custom component when needed.

return (
  <ImageBackground source={require('./image.png')} style={{width: '100%', height: '100%'}}>
    <Text>Inside</Text>
  </ImageBackground>
);

Note that you must specify some width and height style attributes.

Note also that the file path is relative to the directory the component is in.


To add background Image, React Native is based on component, the ImageBackground Component requires two props style={{}} and source={require('')}

 <ImageBackground source={require('./wallpaper.jpg')} style={{width: '100%', height: '100%'}}> 
<....yourContent Goes here...>
    </ImageBackground>

Two options:

  1. Try setting width and height to width and height of the device screen
  2. Good old position absolute

Code for #2:

 render(){
    return(
        <View style={{ flex: 1 }}>
           <Image style={{ width: screenWidth, height: screenHeight, position: 'absolute', top: 0, left: 0 }}/>
           <Text>Hey look, image background</Text>
        </View>
    )
}

Edit: For option #2 you can experiment with resizeMode="stretch|cover"

Edit 2: Keep in mind that option #2 renders the image and then everything after that in this order, which means that some pixels are rendered twice, this might have a very small performance impact (usually unnoticeable) but just for your information


You have to import background component first to use backgroundimage on your code


const img = '../../img/splash/splash_bg.png';
<ImageBackground  source={{ uri: img }} style={styles.backgroundImage} >
    </ImageBackground>

This worked for me. Reference to RN docs can be found here.I wrote mine by reading this- https://facebook.github.io/react-native/docs/images.html#background-image-via-nesting


.hero-image {
  background-image: url("photographer.jpg"); /* The image used */
  background-color: #cccccc; /* Used if the image is unavailable */
  height: 500px; /* You must set a specified height */
  background-position: center; /* Center the image */
  background-repeat: no-repeat; /* Do not repeat the image */
  background-size: cover; /* Resize the background image to cover the entire container */
}

look result


I think this will help u..

import React, { Component } from 'react';
import { homePageStyles } from '../styles/Style';
import { Text, ImageBackground } from 'react-native';
import HomePageWallpaper from '../images/homePageWallpaper.jpg';

export default class Home extends Component {
    render() {
        return (
            <ImageBackground source={HomePageWallpaper} style={{ flex: 1, justifyContent: 'center', width: null, height: null }}>
                <Container>                    
                    <Content>
                        <Text style={homePageStyles.description_text}>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</Text>
                    </Content>
                </Container >
            </ImageBackground>
        );
    }
}

ImageBackground is a very simple and useful component.Put your component inside ImageBackground as a nested component and tweak a position of your component by using position.

Here's an example.

_x000D_
_x000D_
<ImageBackground_x000D_
  source={{ uri: hoge }}_x000D_
  style={{_x000D_
    height: 100,_x000D_
    width: 100,_x000D_
    position: 'relative', _x000D_
    top: 0,_x000D_
    left: 0_x000D_
  }}_x000D_
>_x000D_
  <Text_x000D_
    style={{_x000D_
      fontWeight: 'bold',_x000D_
      color: 'white',_x000D_
      position: 'absolute', _x000D_
      bottom: 0, _x000D_
      left: 0_x000D_
    }}_x000D_
  >_x000D_
    Hello World_x000D_
  </Text>_x000D_
</ImageBackground>
_x000D_
_x000D_
_x000D_