Render an Animated GIF in a React component

avatar

Borislav Hadzhiev

Tue Apr 19 20222 min read

banner

Photo by Alex Radelich

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.

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;

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 of these 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.