Probosckie
Probosckie

Reputation: 1812

Add animated gifs to react web apps

I'm trying to define a transition state for my react web application when I'm publishing data to backend.

I want to show an animated gif in my render method.

So I import the gif image (like this enter image description herehttps://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif )

using a simple import

import logo from '../assets/load.gif'

and add it to my render

like:

<img src={logo} alt="loading..." />

but I get an error in my react-dev server terminal

unknown character

How to add animated gif's to a plain react SPA.

Upvotes: 20

Views: 156238

Answers (6)

Namah
Namah

Reputation: 79

Your error could be because your Webpack doesn't know how to handle the .gif file type. To fix this, configure Webpack to handle .gif files using an appropriate loader.

Here's how you can configure Webpack to handle .gif files using the file-loader:

  1. Install the file-loader:
    npm install file-loader --save-dev
    
  2. Add a rule for handling .gif files in your Webpack configuration file (webpack.config.js or webpack.config.ts):
    module.exports = {
    // Other webpack configuration options...
    module: {
      rules: [
        // Other rules...
        {
          test: /\.gif$/,
          use: [
            {
              loader: 'file-loader',
              options: {
                name: '[name].[ext]',
                outputPath: 'images/', // Output directory for the images
              },
            },
          ],
        },
      ],
    },
    };
    
    
  3. In case you want to handle other images as well. You can configure the test parameter as follows:
    test: /\.(png|jpe?g|gif)$/i
    
    This will handle .png, .jpg, .jpeg and .gif files using the file-loader.

Upvotes: 0

Muhammad Rahamni
Muhammad Rahamni

Reputation: 113

Check this answer if you get this error in typescript. or nothing shows up in js

'StaticImageData' is not assignable to type 'string'

Upvotes: 0

Israel
Israel

Reputation: 11

You just have to modify the path

Try something like:

import load from './assets/load.gif'

Upvotes: 0

Om Fuke
Om Fuke

Reputation: 662

import logo from './gifPath.gif'

<img src={logo} alt="loading..." />

I used this and worked for me as I downloaded the gif

Upvotes: 2

Bharath
Bharath

Reputation: 365

You can also use require('path') method

The require() method fetches the images and converts it to data URI format Read about Data URI here

<img src={require('../assets/load.gif')} alt="loading..." />

Upvotes: 16

Alex
Alex

Reputation: 449

I had a version that used a URL however, it stopped working. I found a site that you can download the spinner as a GIF, then I put that .gif into my images folder. From there you can use:

import logo from '../assets/load.gif'

&

<img src={logo} alt="loading..." />

Upvotes: 38

Related Questions