0

I am using react native for one of my project.

I am setting state with an image url, and then I wanted it to use this state in Image, but its not working

Image path: ../../assets/images/image.png

setSplashImage(image);

Then in Image tag:

<Image
  source={require(splashImage)}
  style={{
    height: 100,
    width: 100,
  }}
/>

But this is not working

pratteek shaurya
  • 850
  • 2
  • 12
  • 34
  • Where is `setSplashImage(image);` located? Maybe `splashImage` doesn't have the correct uri when it's rendered. – Dark Matter Jun 05 '23 at 14:18

1 Answers1

0

You are getting an error because you are trying to use the require() function to load an image from a local file. If you use function like that you can use Image.asset() function.

import React, { useState } from 'react';
import { Image, StyleSheet } from 'react-native';

const App = () => {
  const [splashImage, setSplashImage] = useState('');

  const loadImage = async () => {
    const image = await Image.asset(splashImage);
    setSplashImage(image);
  };

  useEffect(() => {
    loadImage();
  }, []);

  return (
    <Image
      source={splashImage}
      style={{
        height: 100,
        width: 100,
      }}
    />
  );
};

export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>