Image Rendering in ReactJs
ReactJs is a plug and play type of framework targeted primarily to build Web Application. With beginner level knowledge of Javascript, one can get their hands dirty in ReactJs. In the modular approach of building a dynamic and beautiful interface which user will love to interact with React provide quite an edgy solution of the problem faced with developing a web application with HTML, CSS, Javascript.
Though React provides almost every solution of interface development by providing inline-CSS, modular-CSS but one problem that beginner often faces is the image not displaying even after providing the right path in the src attribute of the img tag. Things soon get frustrating that why on earth is the image not loading. Folks start to frantically scroll through long StackOverflow answers, which again leads to more doubts that providing a way out. So taking the importance of image in concern we’ll try to explain the process of rendering(displaying) an image in the creation of a Web-App with one of the popular Javascript framework ReactJs.
Common approach coming from Vanilla HTML ✔️
In general HTML, we generally like to keep all the static files(CSS and images) in the same directory as our HTML file.
Issues for following the same approach in ReactJs🚩
While all other things of HTML work in ReactJs but the image loading will not lead to the undesired output.
Want to read this story later? Save it in Journal.
Following the same structure i.e storing the image(demo-img.png) in the same directory as the file(App.js) which will render the image. The result will be quite unsatisfactory.
The solution of the Problem🏁
The solution is easier than deducing the problem 😋 .
To quickly get out of this situation there a few steps needed to follow:
1. Store the image in the public folder
2. define the src attribute the right way
Please pay attention to the src attribute of the img tag. The path is defined relative to the index.html file which is located in the public folder.
The common good approach for storing the static content is creating an assets folder in the public folder and then storing contents in their respective folders. For example :
Now you’re ready to display that beautiful piece digitized information wherever you want. Hope this helps.
More from Journal
There are many Black creators doing incredible work in Tech. This collection of resources shines a light on some of us: