Last updated: Apr 6, 2024
Reading time·2 min
To render an animated gif in a React component:
import myGif from './path-to-my-gif.gif'
.img
element that shows the gif, e.g. <img src={myGif} alt="" />
.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;
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.
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'
.
src
directory of your project.require()
syntaxIf you are unable to load the GIF using the ES6 modules import/export syntax, try using require.
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 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.
You can learn more about the related topics by checking out the following tutorials: