1. Introduction
In a React application we often have to use images. In this tutorial, we’ll see how to add and display images in React application.
2. Adding images from file location
Suppose the images are stored in the src > images folder. An image can be imported in the component and used in the src attribute.
import CortanaImage from "./images/cortana.png";
function Image(props) {
return (
<div>
<img src={CortanaImage} />
</div>
);
}
export default Image;
3. Adding images from the URL
If the image is not stored locally and is on remote server then image can be added to the component like the following:
function Image(props) {
var imageUrl = "https://images.unsplash.com/photo-1617854818583-09e7f077a156";
return (
<div>
<img src={imageUrl} />
</div>
);
}
export default Image;
4. Pass image in props
Suppose you want to pass the image in the props then you can do so like other props. In the following example, App component is passing CortanaImage to the Image component.
import Image from "./Image";
import CortanaImage from "./images/cortana.png";
function App() {
return (
<div>
<Image image={CortanaImage} />
</div>
);
}
export default App;
function Image(props) {
return (
<div>
<img src={props.image} />
</div>
);
}
export default Image;
5. Important point to note
If the image is less than 9.7kb, the image gets inlined. If the image is more than 9.7kb, it is treated as a separate file.
In this example, SiriImage is less than 9.7kb and AlexaImage is more than 9.7kb. After import if you print the AlexaImage and SiriImage, observe the output.
import AlexaImage from "./images/alexa.png";
import SiriImage from "./images/siri.png";
function Image(props) {
console.log(AlexaImage);
console.log(SiriImage);
// Code removed for brevity
Output
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAe1BMVEUFoNH///7///8Am88AntAAnd......characters removed for brevity
Image.js:6 /static/media/siri.e6a70a555204b3a1f6f0.png
6. Conclusion
In this tutorial, we learned how to add and display images in React component. Conceptually there is nothing specific adding and displaying images in a React component. Images can be passed as props also which allows to create better React components.
