Importing images from public folder in react
change the src from /public/images
to /images
ReactJS: How to upload images from front-end to public folder
I have come up with a solution. I have found a tutorial that uses NodeJS to upload the file. The file just needs to be sent through an endpoint and on the NodeJS server deal with it like this.
app.post('/upload', (req, res) => {
if (req.files === null) {
return res.status(400).json({ msg: 'No file uploaded' });
}
const file = req.files.file;
file.mv(`${__dirname}/client/public/uploads/${file.name}`, err => {
if (err) {
console.error(err);
return res.status(500).send(err);
}
res.json({ fileName: file.name, filePath: `/uploads/${file.name}` });
});
});
This server uploads the image file to public/uploads folder of the ReactJS client. Then in the response returns the file name and file path.
Image in public folder not loading after deployment
If you're using create-react-app it could be caused by the homepage
value in your package.json
being different than before you deployed:
{
"homepage": "http://yourUsername.github.io/yourProjectName"
}
If that's the case, this will change the default react directory to /yourProjectName
.
So in your jsx you would need to add /yourProjectName
by calling the following path instead:
<img src="./yourProjectName/imageName.png" />
More information about relative paths in the docs here.
Note: You could then create an environment variable and call that instead for better reusability.
How to import image into React from public folder through a json file
Seems like you forget one level
images
in JSON. Code of IMG in component should looks like this:
<img src={data.images.url} alt={data.images.name} />
Related Topics
How to Simulate Key Press Events Programmatically
Onclick Button Get from Database and Display on a Input Field Live
Localstorage Values Get Reset After Refreshing Page and Inserting New Values
How to Set a Value to a File Input in HTML
Using JavaScript to Detect Whether the Url Exists Before Display in Iframe
Check If Second String Is Rotation of Another String
Regular Expression to Get a String Between Two Strings in JavaScript
Convert Date/Time in Gmt to Est in JavaScript
How to Specify Multiple Conditions in an If Statement in JavaScript
Is There Any Memory Limit for Google Chrome Browser
How to Automatic Click a Button on a Webpage
Automatically Force Mobile Browser to Desktop View
Creating a Json Dynamically With Each Input Value Using Jquery
How to Correctly Use Axios Params With Arrays
How to Use Js to Open an HTML Select to Show Its Option List
Input Date Format With Dd/Mm/Yyyy in the Input Field
Regex to Allow Only Certain Special Characters and Restrict Underscore