While this post is a summary of a longer post on Medium, it contains all you need to display images using React.
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>
);
}
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);
}
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>
);
}
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;
Top comments (0)