How to dynamically import images in create-react-app - javascript

I am trying to pass a locally stored image name to a component via props. The problem is
<img src={require(`../assets/img/${iconName}.svg`)} />
is not working. I have bootstrapped the project using create-react-app. The component looks like this:
import React from 'react';
import best from '../../assets/img/best.svg';
import cashback from '../../assets/img/cashback.svg';
import shopping from '../../assets/img/shopping.svg';
const Card = ({iconName}) => {
return (
<>
<img alt="icon" src={require(`../assets/img/${iconName}.svg`)} />
</>
);
};
export default Card;
SVGs are failing to load. Even if I write something like:
<img src={require('../assets/img/best.svg')} />
<img src={`${iconName}`} />
it doesn't work. Can this be an issue with webpack loader in CRA?

Because those are SVGs, I imagine, there's a static number of images you might want to display.
At this point you might need to import them all in the beginning. Depending on the tools that you're using around react the dynamic loading of data may or may not work. Your approach definitely would not work for instance with Next.JS (a framework around react).
so I would suggest just loading them all, putting into a map and using that instead of the dynamic require.
import React from 'react';
import best from '../../assets/img/best.svg';
import cashback from '../../assets/img/cashback.svg';
import shopping from '../../assets/img/shopping.svg';
const icons = Object.freeze({best, cashback, shopping});
const Card = ({iconName}) => (<img alt="icon" src={icons[iconName]} />);
export default Card;

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';

How to remove CSS from global scope and only import to the specific pages in React, Gatsby

Currently, I am trying to implement a keen-slider library(https://www.npmjs.com/package/keen-slider).
For installation, we need to add import 'keen-slider/keen-slider.min.css'.
In that case, the keen slider CSS is added to global, as you know.
The CSS is included globally in the page markup. From my perspective, it should be included only on pages where the slider is used
Is there any solution to solve this problem?
I'm not sure to understand the issue. You can always choose to import a file (CSS or whichever format you want) globally or in a specific file.
For your use-case, as soon as you install the dependency (npm install keen-slider --save), you will be able to import the minified CSS into the needed component. For example:
import React from 'react'
import 'keen-slider/keen-slider.min.css'
import { useKeenSlider } from 'keen-slider/react'
export function IndexPage(){
const [sliderRef, slider] = useKeenSlider()
return <section className="slider-wrapper">
<div ref={sliderRef}>
<div class="keen-slider__slide">1</div>
<div class="keen-slider__slide">2</div>
<div class="keen-slider__slide">3</div>
</div>
</section>
}
With this approach, you will be only importing the keen-slider.min.css in the IndexPage.
I think, you can try to lazily load your component via:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
Also you should do import 'keen-slider/keen-slider.min.css' inside of OtherComponent.
More info here: https://reactjs.org/docs/code-splitting.html

React cant find a module

I am trying to insttall https://github.com/wagerfield/parallax/, I already read the documentation, and I got a sample of how to use it in javascript, I am going to use it in React, so, with that sample and the documentation for react I think my code should works, but it doesnt!, I think maybe there are 2 motives for not work.
1- In my html inside body tag this tag appears:
<noscript>You need to enable JavaScript to run this app.</noscript>
2- When I hover the module that I install via NPM, vscode show me this:
I am using react hooks, here I found information of how to use it https://github.com/wagerfield/parallax/issues/167
And also here on demo samples
https://github.com/wagerfield/parallax/blob/master/examples/pages/simple.html
I have literally hours trying to know whats the problem!
This is my jsx code:
import React, {useEffect, useRef} from 'react';
// #ts-ignore
import Parallax from 'parallax-js';
import BackgroundIMG from '../assets/img/background.jpg';
import Guitar from '../assets/img/guitar.png';
import Layer1 from '../assets/img/layer1.png';
import Layer2 from '../assets/img/layer2.png';
import Layer3 from '../assets/img/layer3.png';
import Layer4 from '../assets/img/layer4.png';
import Layer5 from '../assets/img/layer5.png';
import Layer6 from '../assets/img/layer6.png';
import './styles/Home.css';
const Home = () => {
const sceneEl = useRef(null);
useEffect(() => {
const parallaxInstance = new Parallax(sceneEl.current, {
relativeInput: true,
})
parallaxInstance.enable();
return () => parallaxInstance.disable();
}, [])
return (
<div id="container">
<div id="scene" ref={sceneEl}>
<div dataDepth="1.00"><img src={Layer1} /></div>
<div dataDepth="0.80"><img src={Layer2} /></div>
<div dataDepth="0.60"><img src={Layer3} /></div>
<div dataDepth="0.40"><img src={Layer4} /></div>
<div dataDepth="0.20"><img src={Layer5} /></div>
<div dataDepth="0.00"><img src={Layer6} /></div>
</div>
</div>
)
}
export default Home;
In my browser I can see this:
But it doesn't hace the "parallax" effect 😥.
That's because you are using TS and there is no types declaration on the side of the library. I think you can simply fix this doing exactly what the console shows.
I you don't have a .d.ts file, just create one and add declare module 'parallax-js';
After this, if you didn't have the file yet, add it to the include property of your tsconfig.json file and you should be fine.

Facebook Create React App Build - Add Image As Prop Type

I have a component comment.js
export default function Comment (props) {
return (
<div className="comment-wrapper">
<img src={props.userImage} />
<p className="comment">{props.commentTitle}</p>
</div>
);
}
So I just simply want to have that component in the parent component as
<Comment userImage="IMAGE_LINK" commentTitle="BLAH BLAH" />
Again, I am using the Create-React-App build system from facebook. With that being said I know I can hard code an image using the following
<img src={require(`./images/MY-IMAGE.png`)} />
The code above works perfectly fine for the test image I am trying to load. However, when needed dynamically for the component the issue gets a bit more complex.
Now with the comment.js component above, I cannot do
<img src={require("./images" + {props.userImage})} />
I have taken a look at one thread on this site as well as reading this blog post on the issue and can still not come to a conclusion.
How can I handle image assets being passed as props to a component, in this case?
you can use import
// parent component
import MenuImage from '/img/menu.png'
<Comment image={MenuImage} commentTitle="Title"} />
then on Comment component
export default props => (
<img src={props.image} alt='' />
)

Categories

Resources