Home > Software engineering >  Convert React native http images to local assets
Convert React native http images to local assets

Time:01-09

I am new to React native so I am trying to learn by Github's repository. I've found a small recipe app, but it takes photos from websites (https) and I can't figure out how to change it to local assets.

The repository is https://github.com/instamobile/recipes-app-react-native

By Googling it I guess there should be 'require' before the path, but I am getting error:

JSON value 10 of type NSNumber cannot be converted to a valid URL

The CategoryScreen is rendered by code:

const onPressCategory = (item) => {
    const title = item.name;
    const category = item;
    navigation.navigate("RecipesList", { category, title });
  };

  const renderCategory = ({ item }) => (
    <TouchableHighlight underlayColor="rgba(73,182,77,0.9)" onPress={() => onPressCategory(item)}>
      <View style={styles.categoriesItemContainer}>
        <Image style={styles.categoriesPhoto} source={{ uri: item.photo_url }} />
        <Text style={styles.categoriesName}>{item.name}</Text>
        <Text style={styles.categoriesInfo}>{getNumberOfRecipes(item.id)} recipes</Text>
      </View>
    </TouchableHighlight>
  );
and the DataArray.js code:


export const categories = [
  {
    id: 1,
    name: 'Chicken',
    photo_url: require('./chicken.jpg'),
  },

I've tried so many combinations of the 'source' piece of the code and path, but couldn't figure it out.

Thank you for any advice.

CodePudding user response:

Change your source to source={item.photo_url}. Your Image component will look like below

<Image style={styles.categoriesPhoto} source={item.photo_url} />
  1. For uri, define source as source={{uri:'path'}}
  2. For local images, define source as source={require('path')}
  • Related