Set image url in state and use it then in react native

206 Views Asked by At

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

1

There are 1 best solutions below

0
Joel Jaison On

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>