0

How can I use props with image source to create usable component in react native? How should I change my code?

CategoryBox :

class CategoryBox extends Component{
    render(){
        return(
            <View style={{width: this.props.width, height: this.props.width/2 - 30,
                borderWidth: 0.5, borderColor: '#dddddd',}}>
                <View style={{ flex: 1}}>
                    <Image style={{ flex: 1, width: null, height: null}}
                           source={require(this.props.image)}
                    />
                </View>
                <View style={styles.BoxViewTextHandle}>
                    <Text style={{fontSize: 10, color: '#b63838'}}>{this.props.type}</Text>
                    <Text style={{ fontSize: 12, fontWeight: 'bold'}}>{this.props.name}</Text>
                    <Text style={{ fontSize: 10}}>{this.props.price}$</Text>
                    <StarRating
                        disabled={true}
                        maxStars={5}
                        rating={this.props.rating}
                        starSize={10}
                    />
                </View>
            </View>
        );

    }

}


export default CategoryBox;
Mohsen
  • 1,415
  • 1
  • 13
  • 26

2 Answers2

1

Require it's not dynamic.

So you should pass require("someString") from your this.props.image and then :

<Image style={{ flex: 1, width: null, height: null}}
   source={this.props.image}
/>

More details about How use require?

Mohsen
  • 1,415
  • 1
  • 13
  • 26
0

I think the best way to do this is.

export const Icons = { icon:require("something") }

Then create a Image component with any name and it can look like

<AppImage source={Icons.icon} styles={your styles}/>

You can reuse both the images const and AppImage too.

Ashwin Mothilal
  • 2,462
  • 1
  • 16
  • 21