Render an Animated GIF in a React component

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
2 min

banner

# Render an Animated GIF in a React component

To render an animated gif in a React component:

  1. Import the gif as import myGif from './path-to-my-gif.gif'.
  2. Add an img element that shows the gif, e.g. <img src={myGif} alt="" />.
App.js
import myGif from './react-select-option-array.gif'; const App = () => { return ( <div> <h2>Hello world</h2> <img src={myGif} alt="my-gif" /> </div> ); }; export default App;

react render animated gif

If you want to try out the example, right-click on the gif above, click "Save image as" and download it to the src directory of your React app.

We imported the animated gif just like we would import any other image in React.

It's very important to specify the correct path that points to the gif and explicitly write the extension when importing.

The code sample above assumes that the gif is located in the same directory as the App.js file.

For example, if your gif is located one directory up from your component, you would import it as import myGif from '../react-select-option-array.gif'.

Make sure your gif is located in the src directory of your project.

# Try using the require() syntax

If you are unable to load the GIF using the ES6 modules import/export syntax, try using require.

App.js
const App = () => { return ( <div> <h2>Hello world</h2> <img src={require('./react-select-option-array.gif')} alt="my-gif" /> </div> ); }; export default App;

try using the require syntax

This code sample achieves the same result as the previous one but uses the CommonJS require syntax to import the gif.

Just like in the previous example, the import path assumes that the gif is located in the same directory as the App.js file.

Both approaches should work in a modern React.js application. However, it's much more common to use the ES6 import/export syntax to import an image or a GIF in React.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.