DEV Community

Lorenzo Zarantonello
Lorenzo Zarantonello

Posted on • Edited on • Originally published at Medium

Display Images In React

While this post is a summary of a longer post on Medium, it contains all you need to display images using React.

React logo

Images In Source Folder

The first way to import images in React is by adding them to the source folder of your application.

Thanks to webpack, it is possible to import a file right in a JavaScript module.



import logo from './logo.svg'

function App() {
  return (
    <div>
      <img src={logo} className="App-logo" alt="logo" />
    </div>
  );
}



Enter fullscreen mode Exit fullscreen mode

Using CSS

If the image is inside the src folder, you could also add it using CSS as follows:



.logo {
  background-image: url(./logo.png);
}


Enter fullscreen mode Exit fullscreen mode

Images In Public Folder

The second way to import images in React is by adding them to the public folder of your application.

Using the public folder allows us to reference the image in an image tag.

This is a key difference! Files placed in the public folder will be accessible to the client at the root of the application.

Everything inside the public folder is available to the app, so we can simply point the src property of the image tag to the correct location of the file.



function App() {
  return (
   <div>
     <img src="./logo.svg" className="App-logo" alt="logo" />
   </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

SVG as ReactComponent

If you are using React v16.3 or higher you can also import SVGs directly as React components.



import { ReactComponent as Logo } from './logo.svg'

function App() {
  return (
    <div>
       <Logo />  // React Component
    </div>
  );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️