Reactjs and Images in Public Folder

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



Leave a reply



Submit