Frameworks like React were created to make web design and development easy, the downside for frameworks, however, is that things don’t naturally flow the way they ought to like building from scratch. One of the problems I have encountered while picking up React is working images on my PC and it’s quite surprising that I couldn’t find a solution online(even StackOverflow) so I had to figure things on my own. In this short article, I will walk you through how you can work with local images in React (I assume you already know the basics of react so I will skip some things to save time :) )
(1) Create a new react app or use an existing one
npx create-react-app working-with-images
(2) Navigate to where the image(s) is/are on your PC and copy it
(3) Navigate to the react app you created in step 1 and open the public folder
(4) Create a new folder say images
(5) Paste your image(s) in this new folder
(6) Open up App.js in your desired text editor or IDE and clear the content in the header
(7) Create an img tag, in the src attribute, enter the directory images in curly braces followed by a forward slash and the name of the image as shown below
<img src={'images/1.jpg'} alt="A text describing the image" width="500px" />
(8) Start your server (npm start), your image will show up correctly as shown below
npm start
VERY IMPORTANT: Your images must be in the public folder
Top comments (0)