template literals with import images - javascript

<img alt="placeholder" src={ALL.file1.default}></img>
The above works and renders a picture.
I'm trying to use template literals to make the 1 a dynamic variable.
<img alt="placeholder" src={`${ALL.file`${randomnum}`.default}`}></img>
<img alt="placeholder" src={ALL.file`${randomnum}`.default}></img>
Both these don't seem to work as I get an error
Attempted import error: 'file' is not exported from '../images/icons/' (imported as 'ALL').
I imported all the pictures using a index.js in the images folders exporting all of them individually then importing them with:
import * as ALL from "../images/icons/";
Am I using the template literal incorrectly, or does it have something to do with the import conflicting method?
Any help would be appreciated.
Thanks in advance.

Remember when you use dynamic properties you need to use the [] syntax.
In your example, it would go like this:
<img alt="placeholder" src={ALL[`file${randomnum}`].default}></img>

Related

Using SVG from assets folder into component in component folder not working

I'm new and still learning ReactJS, one issue that's stumping me is trying to use an SVG image I made in Vectornator from my assets folder to a header component in my component folder. It works fine when I made the mockup in HTML and I didn't had this issue when working on an Angular project last semester. Is there a fix or should I switch back to Angular and give up learning React lol. Also I'm using CRA since I just found out there's a lot of other ways to create a React app, chaos for a later date.
I don't know if it has any issue with folder structure because wherever I put the image it gives me this error.
Error Message
This is how my folder structure looks like
Folder Structure
And this is my code. I tried doing this through using an img tag and by making the SVG a react component but nothing works to display the image.
import DVLogo from "../assets/DVLogo.svg";
// import {ReactComponent as DVLogo} from "./assets/DVLogo.svg";
const Header = () => {
return (
<header className="header">
{/* <div>
<DVLogo />
</div> */}
<img src={DVLogo} alt="Logo"/>
<h2 className="header-name">DV</h2>
<nav>
<ul className="nav-links">
<li><a></a>Search</li>
<li><a></a>Collections</li>
<li><a></a>About</li>
<li><a></a>Decks</li>
</ul>
</nav>
<a className="login-btn"><button>Login</button></a>
</header>
);
};
export default Header;
Thanks in advance for any help.
When I use ../ instead of ./
Error #2 part 1
Error #2 part 2
You are not in the correct directory.
When you import your image you need to:
import MyLogo from "../assets/DVLogo.sv" // Note the 2 dots (..)
If you are using the following format:
<img src={DVLogo} alt="Logo"/> // WRONG
You can not pass only DVLogo but also need the src:
<img src={DVLogo.src} alt="Logo"/> // CORRECT
I think it's weird that I'm posting an answer to my own question but maybe it might help someone else or if I forget I can always come back to this.
But what I did was create a component returning the actual SVG code and change the syntax of them to match the JSX.
Examples:
stroke-width to strokeWidth
style="fill-rule: nonzero;" to style={{ fillRule: "nonzero"}}
vectornator:layerName="card" to vectornatorlayername="card"
Below is pics of both for a more in-depth look at the differences if anyone is interested. Thank you guys for helping. Not changing majors yet!
Original SVG file
New SVG component

How to set the src attribute in img tag in JSX 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';

Images not loading when relative path is used in React

I was importing the images previously like this in React:
import person from '../images/image1.png'
And then using them like this:
<img src={person} alt="" />
Now I want to specify the path in the src itself due to some reason, like this:
<img src="../images/image1.png" alt="" />
But it's not working even though it should.
There are two ways to add images in your JSX with Create React App. The first one is to use import like you did, to import an image that is somewhere in the src folder, like so:
import person from '../images/image1.png'
<img src={person} alt="" />
The second one is to give an image's path to <img>'s src attribute, but it's always relative to the public folder, in a way that the path should starts with /, and / means public folder.
See Adding Images, Fonts, and Files and Using the Public Folder on Create React App's documentation.
For your second attempt to work, you could put images folder inside public folder, and get your images like so:
<img src="/images/image1.png" alt="" />
If your React app will be in a sub folder when deployed, for the second way to work, you should add in your package.json this "homepage":"www.example.com/folder", and use process.env.PUBLIC_URL as below.
<img src={process.env.PUBLIC_URL + "/images/image1.png"} alt="" />

React Image path is correct but it doesn't find/import it

I have images in one folder while one of the images is getting imported easily the second one isn't being found
import img from '../Img/a292.jpg';
// import img from '../Img/building5.png';
export default function First() {
return (
<section id="first" className="d-flex justify-content-center align-items-center">
<img src={img} alt="img"/>
</section>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
My screen
when importing building5.png
when importing a292.jpg
EDIT: Things I have tried src={require('../Img/a292.jpg')} and I have tried to convert the image to png because all the PNG-s were working so I thought it's the format that meters,but no didn't work :/
I have an exotic solution, It's happening very rarely but it might happen to you, Change the name to numbers like 123.jpg
It might happen that the letter a is in Russian and English or something like that, just try
Well, I've faced the same issue and I do the following to import images:
Place the image a292.jpg in Public folder.
Now you can directly write in the img src the path as './a292.jpg'. [The path is relative to the Public folder because index.html is present in public folder so when the virtual DOM is rendered it takes the relative path from index.html]

adding images to in react with dynamic links

I have created react app using create-react-app , there is a component which need to be reused multiple times, this component contain <img> tag, image is different for each instance of the component.
I am passing image path as imagePath prop from parent to child component and then that child need to load image from that path.
i can not use
import image from imagePath
because i don't know the path until component is build, and import statement don't work within component body.
I tried doing<img src={imagePath}>
that also don't work, can you point me to right direction?
adding code for further clarification
first approach it doesnt work. content is object passed by parent and content.image have value of ./images/keeper.PNG
import React from 'react';
import image from './images/keeper.PNG'
export default function Project(props)
{
return <div className='projectContainer' >
<div className='projectImage'>
<img src={props.content.image}
alt ='' />
</div>
<div className='.projectDescription'>
<h4>{props.content.name}</h4>
<p>{props.content.intro}</p>
<h5>Technologies and problems</h5>
<p>{props.content.tech}
</p>
</div>
</div> }
second methond <img src={image} alt ='' /> it works fine and show image but as stated above i don't know image path before the component is created
Sample
Parent component
let image = 'https://www.belightsoft.com/products/imagetricks/img/intro-video-poster#2x.jpg'
function Parent(){
return <Child image={image}/>
}
Child component
function Child(props){
return <img src={props.image} alt="icon-image" />
}
or
directly if you import in component
import imagePath from './image.jpg';
function Child(props){
return <img src={imagePath} alt="icon-image" />
}
Try using it this way, where you can pass the imagePath via props
<img src={require(`${props.imagePath}`)} />
This alone will do the job.
When using Webpack you need to require images in order for Webpack to
process them, which would explain why external images load while
internal do not, so instead of img src= {"/imagePath"} you need to
use img src= {require('/imagePath')} replacing imagePath with the
correct image name for each of them. That way Webpack is able to
process and replace the source img.

Categories