DEV Community

Cover image for Working with local images in ReactJS
Aremu Smog
Aremu Smog

Posted on

 

Working with local images in ReactJS

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
Enter fullscreen mode Exit fullscreen mode

(2) Navigate to where the image(s) is/are on your PC and copy it

Alt Text

(3) Navigate to the react app you created in step 1 and open the public folder

Alt Text

(4) Create a new folder say images

Alt Text

(5) Paste your image(s) in this new folder

Alt Text

(6) Open up App.js in your desired text editor or IDE and clear the content in the header

Alt Text

(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" />
Enter fullscreen mode Exit fullscreen mode

(8) Start your server (npm start), your image will show up correctly as shown below

npm start
Enter fullscreen mode Exit fullscreen mode

Alt Text

VERY IMPORTANT: Your images must be in the public folder

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

Learn the ins and outs of Promises and Async/Await!