Buttersnips
Buttersnips

Reputation: 47

Passing Image source to a Component

I have a file main.js that calls a component Home like

 <Home width = {width} }/>

And my home component has an Image like

class Home extends Component{
    render(){
        return(
            <View style = {{width: this.props.width/2,height:this.props.width/2 ,
                borderWidth:0.5,borderColor:'#dddddd'}}>
               <View style = {{flex : 1}}>
               <Image 
               style = {{flex:1,width:null,height:null,resizeMode:'cover'}}
               source = {require(this.props.source)} >
               </Image>
               </View>
               <View style ={{flex:1 , alignItems:'flex-start', 
               justifyContent:'space-evenly', paddingLeft: 10}}>
               <Text style = {{fontSize:14,color:'#b63838'}}> 5 bedroom </Text>
               <Text style = {{fontSize:12 , fontWeight:'bold'}}>North York</Text>
               <Text style = {{fontSize:12 , fontWeight:'bold'}}>$4000</Text>
               </View>
                </View>
        );
    }
}
export default Home;


The image is store locally in an asset folder which can be accessed by require('../assets/Images/Houses/house6.jpeg');

My component has to be called multiple times using different images.
How can I pass the image path to the Home component.

<Home width = {width} source = ??????/>

Upvotes: 2

Views: 970

Answers (2)

Nagama Inamdar
Nagama Inamdar

Reputation: 2857

You have already accessed this.props.source in your home component. As below mentioned export your images in a file to be imported in any component.

Update :

const images = {
    houseImage: require(‘../assets/Images/Houses/house6.jpeg’)
};


export default images;

Home component

import Images from ‘@assets/images’;

<Image style = {{flex:1,width:null,height:null,resizeMode:'cover'}}  source={Images.houseImage} />

Upvotes: 2

arjayosma
arjayosma

Reputation: 550

Try this one:

class ParentClass extends Component {
   construct() {
      this.state = {
         images : [require('../path/to/image1.png'), require('../path/to/image2.png')]
      };
   }

   render = () => {
      // Iterate through this one...
      return(<Home width={width} source={this.state.images[i]});
   }
}

You can't pass something dynamic to a require() function. Read on further here: react native use variable for image file

Upvotes: 0

Related Questions