How to get image from public folder without using Webpack - javascript

I have read a lot of posts on getting image from the public folder with Webpack. However, is there anyway to do so without a Webpack?
My code structure:
./public/logo.png
./src/../source_file.js (which renders an <img> and that needs to be pointed to the logo image
I tried import img from './logo.png' but that is not working. Also tried relative path but reactjs is preventing me from importing anything outside src folder.

As long as your package.json is at the root, this will work:
import logo from '../../public/logo.png';
const MyComponent = () => (<div>
<img src={logo} alt={"logo"} />
</div>);
export default MyComponent;
Otherwise, assuming you are copying your /public folder to the root of your webserver, you can also simply do <img src="/logo.png" alt="logo">

I finally use window.location.origin + "logo.png". Posted here in case anyone want to have a try.

Related

Why is my image not being displayed in React? [duplicate]

How can I load image from local directory and include it in reactjs img src tag?
I have an image called one.jpeg inside the same folder as my component and I tried both <img src="one.jpeg" /> and <img src={"one.jpeg"} /> inside my renderfunction but the image does not show up. Also, I do not have access to webpack config file since the project is created with the official create-react-app command line util.
Update: This works if I first import the image with import img from './one.jpeg' and use it inside img src={img}, but I have so many image files to import and therefore, I want to use them in the form, img src={'image_name.jpeg'}.
First of all wrap the src in {}
Then if using Webpack;
Instead of:
<img src={"./logo.jpeg"} />
You may need to use require:
<img src={require('./logo.jpeg')} />
Another option would be to first import the image as such:
import logo from './logo.jpeg'; // with import
or ...
const logo = require('./logo.jpeg'); // with require
then plug it in...
<img src={logo} />
I'd recommend this option especially if you're reusing the image source.
The best way is to import the image first and then use it.
import React, { Component } from 'react';
import logo from '../logo.svg';
export default class Header extends Component {
render() {
return (
<div className="row">
<div className="logo">
<img src={logo} width="100" height="50" />
</div>
</div>
);
}
}
Inside public folder create an assets folder and place image path accordingly.
<img className="img-fluid"
src={`${process.env.PUBLIC_URL}/assets/images/uc-white.png`}
alt="logo"/>
you need to use require and . default
<img src={require('./logo.jpeg').default} />
You need to wrap you image source path within {}
<img src={'path/to/one.jpeg'} />
You need to use require if using webpack
<img src={require('path/to/one.jpeg')} />
put your images in the public folder or make a subfolder in your public folder and put your images there.
for example:
you put "completative-reptile.jpg" in the public folder, then you can access it as
src={'/completative-reptile.jpg'}
you put completative-reptile.jpg at public/static/images, then you can access it as
src={'/static/images/completative-reptile.jpg'}
the best way for import image is...
import React, { Component } from 'react';
// image import
import CartIcon from '../images/CartIcon.png';
class App extends Component {
render() {
return (
<div>
//Call image in source like this
<img src={CartIcon}/>
</div>
);
}
}
const photo = require(`../../uploads/images/${obj.photo}`).default;
...
<img src={photo} alt="user_photo" />
I had the same problem and after research I managed to solve it by putting the JSON data in a constant in JS, with that I was able to import the image and only inform the import in the JSON object. Example:
import imageImport from './image.png';
export const example = [
{
"name": "example",
"image": imageImport
}
]
<Image source={example.image}/>
You have two ways to do it.
First
Import the image on top of the class and then reference it in your <img/> element like this
import React, { Component } from 'react';
import myImg from '../path/myImg.svg';
export default class HelloImage extends Component {
render() {
return <img src={myImg} width="100" height="50" />
}
}
Second
You can directly specify the image path using require('../pathToImh/img') in <img/> element like this
import React, { Component } from 'react';
export default class HelloImage extends Component {
render() {
return <img src={require(../path/myImg.svg)} width="100" height="50" />
}
}
For people who want to use multiple images of course importing them one by one would be a problem. The solution is to move the images folder to the public folder. So if you had an image at public/images/logo.jpg, you could display that image this way:
function Header() {
return (
<div>
<img src="images/logo.jpg" alt="logo"/>
</div>
);
}
Yes, no need to use /public/ in the source.
Read further: https://daveceddia.com/react-image-tag/.
If you dont want to put your image inside public folder use below syntax
src={require("../../assets/images/img_envelope.svg").default}
I found another way to implement this (this is a functional component):
const Image = ({icon}) => {
const Img = require(`./path_to_your_file/${icon}.svg`).ReactComponent;
return <Img />
}
Hope it helps!
First you have to import the image
import logo from './logo.jpeg'; // with import
then plug it in...
<img src={logo} />
That's it.
As some mentioned in the comments, you can put the images in the public folder. This is also explained in the docs of Create-React-App: https://create-react-app.dev/docs/using-the-public-folder/
Step 1 : import MyIcon from './img/icon.png'
step 2 :
<img
src={MyIcon}
style={{width:'100%', height:'100%'}}
/>
For the require method to work, I had to add ".default", like this:
<img src={require('./path/to/image.svg').default} />
I actually just ran into this very same problem and if you move your image file from the ./public directory to the ./src directory you can import or require and either will render.
I have also tested both with the image as well as src attributes in the component and they both worked.
After I tried using the ../ to indicate the exact folder the jpg was located in I was given a usable error that allowed me to make the easy fix.
the computer was kind enough to give me a usable error message.
My answer is basically very similar to that of Rubzen. I use the image as the object value, btw.
Two versions work for me:
{
"name": "Silver Card",
"logo": require('./golden-card.png'),
or
const goldenCard = require('./golden-card.png');
{ "name": "Silver Card",
"logo": goldenCard,
Without wrappers - but that is different application, too.
I have checked also "import" solution and in few cases it works (what is not surprising, that is applied in pattern App.js in React), but not in case as mine above.
I usually prefer to put images in a public folder as recommended in the official documentation.
1. Put your image into public folder. e.g, public/images/image.png
2. use directly into <img>. E.g, <img src="images/image.png" />
As it is in public folder, it will directly use those images. No need to import them.
I have used this way, and it works... I hope you useful.
const logofooter = require('../../project-files/images/logo.png');
return(
<div className="blockquote text-center">
<img src={logofooter} width="100" height="80" />
<div/>
);
import React from "react";
import image from './img/one.jpg';
class Image extends React.Component{
render(){
return(
<img className='profile-image' alt='icon' src={image}/>
);
}
}
export default Image
You could create a file named for instance images.js and reference all your app resources there, later importing that component in all your other component where you would need to display images
I wanted to import multiple images and pass them to different components. It turned out that I need to import multiple images only once and I can use them in any component by passing a prop.
import whiskey from './img/whiskey.jpg';
import hazel from './img/hazel.jpg';
import tubby from './img/tubby.jpg';
Let's make an object.
dog = [
{ name: "Whiskey", src: whiskey },
// ...
]
And display the image
<img src={dog.src}></img>
For me, I wanted to call and use an image within an array block from an image folder. Using the "require" method and concatenating with "default" like this, solved it for me.
in my slide-data.js page:
export const sliderData = [
{
image: require('../../../assets/your-image.jpg').default,
desc: "simple description",
},
You can then use e.g in a separate page, by writing
import { sliderData } from "../../slider-data";
{sliderData.map((slide, index) => {
return (
<div className="" key={index}>
<img src={slide.image} alt="slide" className="image overlay " />
</div>
);
})}
import image from './img/one.jpg';
class Icons extends React.Component{
render(){
return(
<img className='profile-image' alt='icon' src={image}/>
);
}
}
export default Icons;
Well, you all know the answer to the question asked by now, but I am posting this answer to the question which most of you might be wondering after reading other answers:
Question: How the hell am I suppose to import 50 or 100 files:)
Answer: I suggest you make an api (.json) file and in that put the links to all the images and call the api.
That's by far the best way to import files in bulk very easily, although it will take some time and knowledge, which If you don't already know.
An addition, if you have multiple images to import, just and an entry point file, namely a js file the imports all the images and exports them out. Then all you have to do is import all the images from one file.
What I mean is this:
Before app.js
import logo from './logo.png';
import cake from '../assets/cake.jpg';
import image from '../assets/shine.jpg';
src/imageEntry.js
import logo from './logo.png';
import cake from '../assets/cake.jpg';
import image from '../assets/shine.jpg';
export {
logo,
cake,
image
};
After src/app.js
import { cake, logo, image} from './imageEntry.js';

Image Not Showing React Props [duplicate]

How can I load image from local directory and include it in reactjs img src tag?
I have an image called one.jpeg inside the same folder as my component and I tried both <img src="one.jpeg" /> and <img src={"one.jpeg"} /> inside my renderfunction but the image does not show up. Also, I do not have access to webpack config file since the project is created with the official create-react-app command line util.
Update: This works if I first import the image with import img from './one.jpeg' and use it inside img src={img}, but I have so many image files to import and therefore, I want to use them in the form, img src={'image_name.jpeg'}.
First of all wrap the src in {}
Then if using Webpack;
Instead of:
<img src={"./logo.jpeg"} />
You may need to use require:
<img src={require('./logo.jpeg')} />
Another option would be to first import the image as such:
import logo from './logo.jpeg'; // with import
or ...
const logo = require('./logo.jpeg'); // with require
then plug it in...
<img src={logo} />
I'd recommend this option especially if you're reusing the image source.
The best way is to import the image first and then use it.
import React, { Component } from 'react';
import logo from '../logo.svg';
export default class Header extends Component {
render() {
return (
<div className="row">
<div className="logo">
<img src={logo} width="100" height="50" />
</div>
</div>
);
}
}
Inside public folder create an assets folder and place image path accordingly.
<img className="img-fluid"
src={`${process.env.PUBLIC_URL}/assets/images/uc-white.png`}
alt="logo"/>
you need to use require and . default
<img src={require('./logo.jpeg').default} />
You need to wrap you image source path within {}
<img src={'path/to/one.jpeg'} />
You need to use require if using webpack
<img src={require('path/to/one.jpeg')} />
put your images in the public folder or make a subfolder in your public folder and put your images there.
for example:
you put "completative-reptile.jpg" in the public folder, then you can access it as
src={'/completative-reptile.jpg'}
you put completative-reptile.jpg at public/static/images, then you can access it as
src={'/static/images/completative-reptile.jpg'}
the best way for import image is...
import React, { Component } from 'react';
// image import
import CartIcon from '../images/CartIcon.png';
class App extends Component {
render() {
return (
<div>
//Call image in source like this
<img src={CartIcon}/>
</div>
);
}
}
const photo = require(`../../uploads/images/${obj.photo}`).default;
...
<img src={photo} alt="user_photo" />
I had the same problem and after research I managed to solve it by putting the JSON data in a constant in JS, with that I was able to import the image and only inform the import in the JSON object. Example:
import imageImport from './image.png';
export const example = [
{
"name": "example",
"image": imageImport
}
]
<Image source={example.image}/>
You have two ways to do it.
First
Import the image on top of the class and then reference it in your <img/> element like this
import React, { Component } from 'react';
import myImg from '../path/myImg.svg';
export default class HelloImage extends Component {
render() {
return <img src={myImg} width="100" height="50" />
}
}
Second
You can directly specify the image path using require('../pathToImh/img') in <img/> element like this
import React, { Component } from 'react';
export default class HelloImage extends Component {
render() {
return <img src={require(../path/myImg.svg)} width="100" height="50" />
}
}
For people who want to use multiple images of course importing them one by one would be a problem. The solution is to move the images folder to the public folder. So if you had an image at public/images/logo.jpg, you could display that image this way:
function Header() {
return (
<div>
<img src="images/logo.jpg" alt="logo"/>
</div>
);
}
Yes, no need to use /public/ in the source.
Read further: https://daveceddia.com/react-image-tag/.
If you dont want to put your image inside public folder use below syntax
src={require("../../assets/images/img_envelope.svg").default}
I found another way to implement this (this is a functional component):
const Image = ({icon}) => {
const Img = require(`./path_to_your_file/${icon}.svg`).ReactComponent;
return <Img />
}
Hope it helps!
First you have to import the image
import logo from './logo.jpeg'; // with import
then plug it in...
<img src={logo} />
That's it.
As some mentioned in the comments, you can put the images in the public folder. This is also explained in the docs of Create-React-App: https://create-react-app.dev/docs/using-the-public-folder/
Step 1 : import MyIcon from './img/icon.png'
step 2 :
<img
src={MyIcon}
style={{width:'100%', height:'100%'}}
/>
For the require method to work, I had to add ".default", like this:
<img src={require('./path/to/image.svg').default} />
I actually just ran into this very same problem and if you move your image file from the ./public directory to the ./src directory you can import or require and either will render.
I have also tested both with the image as well as src attributes in the component and they both worked.
After I tried using the ../ to indicate the exact folder the jpg was located in I was given a usable error that allowed me to make the easy fix.
the computer was kind enough to give me a usable error message.
My answer is basically very similar to that of Rubzen. I use the image as the object value, btw.
Two versions work for me:
{
"name": "Silver Card",
"logo": require('./golden-card.png'),
or
const goldenCard = require('./golden-card.png');
{ "name": "Silver Card",
"logo": goldenCard,
Without wrappers - but that is different application, too.
I have checked also "import" solution and in few cases it works (what is not surprising, that is applied in pattern App.js in React), but not in case as mine above.
I usually prefer to put images in a public folder as recommended in the official documentation.
1. Put your image into public folder. e.g, public/images/image.png
2. use directly into <img>. E.g, <img src="images/image.png" />
As it is in public folder, it will directly use those images. No need to import them.
I have used this way, and it works... I hope you useful.
const logofooter = require('../../project-files/images/logo.png');
return(
<div className="blockquote text-center">
<img src={logofooter} width="100" height="80" />
<div/>
);
import React from "react";
import image from './img/one.jpg';
class Image extends React.Component{
render(){
return(
<img className='profile-image' alt='icon' src={image}/>
);
}
}
export default Image
You could create a file named for instance images.js and reference all your app resources there, later importing that component in all your other component where you would need to display images
I wanted to import multiple images and pass them to different components. It turned out that I need to import multiple images only once and I can use them in any component by passing a prop.
import whiskey from './img/whiskey.jpg';
import hazel from './img/hazel.jpg';
import tubby from './img/tubby.jpg';
Let's make an object.
dog = [
{ name: "Whiskey", src: whiskey },
// ...
]
And display the image
<img src={dog.src}></img>
For me, I wanted to call and use an image within an array block from an image folder. Using the "require" method and concatenating with "default" like this, solved it for me.
in my slide-data.js page:
export const sliderData = [
{
image: require('../../../assets/your-image.jpg').default,
desc: "simple description",
},
You can then use e.g in a separate page, by writing
import { sliderData } from "../../slider-data";
{sliderData.map((slide, index) => {
return (
<div className="" key={index}>
<img src={slide.image} alt="slide" className="image overlay " />
</div>
);
})}
import image from './img/one.jpg';
class Icons extends React.Component{
render(){
return(
<img className='profile-image' alt='icon' src={image}/>
);
}
}
export default Icons;
Well, you all know the answer to the question asked by now, but I am posting this answer to the question which most of you might be wondering after reading other answers:
Question: How the hell am I suppose to import 50 or 100 files:)
Answer: I suggest you make an api (.json) file and in that put the links to all the images and call the api.
That's by far the best way to import files in bulk very easily, although it will take some time and knowledge, which If you don't already know.
An addition, if you have multiple images to import, just and an entry point file, namely a js file the imports all the images and exports them out. Then all you have to do is import all the images from one file.
What I mean is this:
Before app.js
import logo from './logo.png';
import cake from '../assets/cake.jpg';
import image from '../assets/shine.jpg';
src/imageEntry.js
import logo from './logo.png';
import cake from '../assets/cake.jpg';
import image from '../assets/shine.jpg';
export {
logo,
cake,
image
};
After src/app.js
import { cake, logo, image} from './imageEntry.js';

ReactJS: How to properly link to a download file?

I have a manual.pdf file that I need to attach to my document.
The conventional wisdom would be to link the file source in the href attribute of an <a> tag:
<a href="../assets/img/manual.pdf" download>Manual</a>
React seems to not like it, I assume. Failed-No file error is given upon click on the <a> tag.
When it is an <img> tag with a local file, I would import the source import logo from '../assets/img/logo.svg';, then pass it to the src attribute like so <img src={logo} alt="brand logo" />.
I tried it - no use.
giving the absolute path - no use.
giving a relative path - no use.
It seems that it does not work the same way with <a> tags.
How do I properly link local files in a React Project?
P.S. I have heard of React routes, but I am not linking to any page, it is for downloading a file.
Try this
<Link to="/files/manual.pdf" target="_blank" download>Download</Link>
Where /files/manual.pdf is inside your public folder
Try this one https://www.npmjs.com/package/file-saver (FileSaver.js)
//function for saving file
const saveManual = () => {
fileSaver.saveAs(
process.env.REACT_APP_CLIENT_URL + "../assets/img/manual.pdf",
"manual.pdf"
);
};
//button for calling
<button onClick={saveManual}>
Manual
</button>

how to use images in reactjs

Here is my code.
I have an images folder inside the "src" folder and I want to use the images inside of my components/Myapp.component.js
import React from 'react';
import imageOne from '../img/cool-img.jpg';
function Myapp() {
return (
<div className="myapp">
<h1>import image<h1>
<img src={imageOne} alt="import-img" />
<h1>relative-path image</h1>
<img src="../img/cool-img.jpg" alt="relativepath-img" />
</div>
);
}
export default MyApp;
My problem is that the first import image works fine but the second relative path image does not work.
There are some common ways to import images in the ReactJs application. for such cases that images have separated server, it's so simple just call images like below:
<img src="https://images.cdn.com/sample-image.png" alt="sample-image" />
But if the images are for the application not for a show to the users, like images of UI design, there are two common ways:
Use copy-webpack-plugin and put all photos inside a folder then after build and serve, you should serve this folder and then you can call them from your link(eg: assume we run the project on the localhost:3000):
<img src="https://localhost:3000/sample-image.png" alt="sample-image" />
Just like your first trick, put all photos inside a folder and import them inside each component you need, then use it:
import sampleImage from '..[pathToAssets]/assets/imgs/sample-image';
~~~
<img src={sampleImage} alt="sample-image" />
I hope this answer helps you.
This is not working because <img src="../img/cool-img" alt="relativepath-img" /> image src is not resolved using Webpack file-loader, when you use import statement for a file, it will be checked first by Webpack and it will use the appropriate loader for the file type, in your case its an image so it will use file-loader, it will then handover the responsibility for it to handle the resolve of your file path,
If for example do a console.log(imageOne) it will log a path for your image, based on your public file path specified in your Webpack config file.
<img src="../img/cool-img" alt="relativepath-img" /> on the other hand will be printed as is since it written inside JSX code and it will not resolve the real path for your public folder.
So you should be using the first way (importing files) to resolve your files/images path.

How to set image url in ReactJS

I am trying to set the path of an Image inside a img tag in ReactJS but It is not showing...
This is what I tried...
import React, { Component } from "react";
import { Carousel } from "react-responsive-carousel";
import "react-responsive-carousel/lib/styles/carousel.css";
export default class CarouselComponent extends Component {
render() {
return (
<Carousel
showArrows
emulateTouch
infiniteLoop
autoPlay
interval={2000}
onChange={this._onChange}
onClickItem={this._onClickItem}
onThumbClick={this._onClickThumb}
>
<div>
<img src="../images/sample1.jpg" /> {/*not working*/}
<p className="legend">Welcome to W.W Coders</p>
</div>
<div>
<img src="http://placehold.it/1080x300?" />
<p className="legend">Faculty of Computing</p>
</div>
<div>
<img src="http://placehold.it/1080x300?" />
<p className="legend">Faculty of Engineering</p>
</div>
<div>
<img src="http://placehold.it/1080x300?" />
<p className="legend">Faculty of Business Management</p>
</div>
</Carousel>
);
}
}
And this is my folder structure
Can someone tell me where I have went wrong?
Assuming you are using webpack or a similar bundler for your code compilation, you can use the file-loader to ensure that the image is copied to the compile folder, and you get the path pointing to it as such:
import imagePath from '../images/sample.jpg'
...
<img src={imagePath} />
From your project structure, it looks like the public folder is where you should put all your images. Any files that are accessible by url directly (like images), should be inside this folder. The files inside src and other folders are intended to be built/compiled and not directly accessed via a URL.
You should move your images folder to be inside the public folder. So it would be like:
/public/images/sample1.jpg
Then you would access it like:
src="/images/sample1.jpg"
Assuming you are using create-react-app here's some info about the public folder. It looks like they want you to use a variable for the path, but often you can just use the root (/).

Categories

Resources