skip to Main Content

I currently have this bit of code :

  const renderImage = (imageUrl: string) => {
    if (imageUrl)
      return (<Image style={styles.image} source={require(imageUrl)} />);
    return (<View></View>)
  }

and the error I am getting is : "Invalid call at line 28: require(imageUrl)". I would have thought that the "if(imageUrl)" would have sorted that out.

I have tried but the image is not being rendered:

  const renderImage = (imageUrl: string) => {
    if (imageUrl)
      return (<Image style={styles.image} source={{ uri: imageUrl }} />);
    return (<View></View>)
  }

EDIT: The imageUrl will be null while loading data which is what is causing the error.

2

Answers


  1. make sure you import Image from react native and add styles for width and height:

    <Image style={{ width: 100, height: 100 }}  source={{uri : "https://i.stack.imgur.com/RWR5C.jpg?s=256&g=1"}} />;
    

    Example

    import React from "react";
    import { Image, ImageRequireSource, ImageURISource, View } from "react-native";
    
    
    const imageURI = "https://i.stack.imgur.com/RWR5C.jpg?s=256&g=1";
    
    const assetImage = require("./assets/images/icon.png");
    
    const RenderURIImage = ({ imageURI }: { imageURI: ImageURISource["uri"] }) => {
      return (
        <Image source={{ uri: imageURI }} style={{ width: 100, height: 100 }} />
      );
    };
    
    const RenderAssetImage = ({ image }: { image: ImageRequireSource }) => {
      return <Image source={image} style={{ width: 100, height: 100 }} />;
    };
    
    function App() {
      return (
        <View style={{ flex: 1 }}>
          <RenderURIImage imageURI={imageURI} />
    
          <RenderAssetImage image={assetImage} />
        </View>
      );
    }
    
    Login or Signup to reply.
  2. Please make sure you are passing sizes to image cause image need size to render otherwise it will never render.
    Like this you can add.

    <Image style={{ width: 200, height: 200 }} source={{uri : imgUrl}} />;

    And also you can add default image.

    <Image style={{ width: 200, height: 200 }} source={{uri : imgUrl || defaultImg }} />;

    So you can confirm it whats going on. I hope it will works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search