Search code examples
react-nativeaxiosnodes

How to render local images according to the id of the items fetched from url?


I have created an images folder in assets and I have saved some pictures in it. And I wanted to render those pictures according to the id of the items that I have fetched from the URL, I renamed all those picture according the id of the items fetched. But it is not working. Can anybody help me to figure out or if you have another suggestion to do it I am open for suggestions? Here you can see what I am trying to do:

export default function App() {
      const [material, setMateral] = useState([]);
    useEffect(() => {
        axios
          .get("http://localhost:5000/materals/")
          .then((products) => {
            setMaterial(materials.data.response);
          })
          .catch((err) => {
            console.error(err);
          });
      }, []);
return (
    <View style={styles.container}>
    {material.map((material) => {
            console.log(material);
            const { id, name, categories, genders, brands, price } = material;
            <View style={styles.materialsContainer}>
              <View style={styles.materialsItem}>
                <Image
                  source={"../../assets/images/${id}.jpg"}
                  alt={id}
                  style={styles.thumbnail}
                />
                <Text style={styles.box} numberOfLines={1}>
                  ${id}
                </Text>
                <Text style={styles.box}${name}</Text>
                <Text style={styles.box}${categories}</Text>
                <Text style={styles.box}${genders}</Text>
                <Text style={styles.box}${brands}</Text>
                <Text style={styles.box}$ ${price}</Text>
              </View>
            </View>;
          })}
     );
    }

Here is what I got in the console


Solution

  • Your problem is here:

    <Image
        source={"../../assets/images/${id}.jpg"}
        alt={id}
        style={styles.thumbnail}
    />
    

    You should be using backticks (``) rather than double quotation to perform string interpolation.

    <Image
        source={`../../assets/images/${id}.jpg`}
        alt={id}
        style={styles.thumbnail}
    />
    

    I'm also not sure what you're trying to do in your Text components

    <Text style={styles.box}${name}</Text>
    

    Are you trying to add a '$' as a string before the name? If you're trying to perform string interpolation, the ${} format only works when using backticks. But in this case, you could just do this.

    <Text style={styles.box}>{name}</Text>