Adding Images in React

Hansel and Gretel thought they could find their way with the breadcrumbs they scattered along the path, but there was one thing they didn’t account for—the breadcrumbs had disappeared, and so had their path. Sometimes, even if you're sure your path is correct, if you lose the breadcrumbs, you may not be able to go back. If you have enough imagination, if the child within you who loves to get lost in reading is still alive, and if Evgeny Grinko’s Valse is playing in the background, don’t be afraid of the images that don’t appear even though you’ve correctly written the path while learning React. Fairy tales guide us to the right path, even in software. In this article, I want to talk about a problem I encountered and the solution I found while learning React. As usual, I added my image to my file and expected it to appear on my page by specifying the file path, but the image never showed up. Despite checking the path multiple times, I couldn’t solve the problem, and after some research, I found the solution. There are several ways to add images in React. If you’re thinking of using the traditional method of creating a local "image" folder, putting your images there, and then entering the image path in src, you should scatter pebbles along the path instead of breadcrumbs.

image

When you add your image this way, due to webpack, your images will not be visible. Therefore, you should add elements like images with import.

image

When you import, webpack can correctly position it. This way, you can find Hansel. Another point to note is that your image is now a variable, so you should write it using the logic of declaring variables in React. If you don’t want to deal with any of this, and you never liked the Grimm brothers anyway, we have another method for adding images. If you place your images in the Public folder, you can now enter the path of your image in src. This way, you directly access your image. From a usability perspective, if you have 1000 images and you want to access all of them, it would be more practical to add them to the Public folder instead of importing each one individually.

Copyright ©2023. All rights reserved.