Rendering image in react component - javascript

I am having an issue to render my images from my './src/img' file and have no idea where i'm going wrong...
I have an object which have a key 'image' which return the file name (ie: 'filename.jpg'). As stated before, the images are stored in an 'img' folder in the 'src' one.
in my component, i return the image like this :
<div className='image'>
<img src={require(`../img/${details.image}`)} alt={details.name} />
{
console.log(details.image)
}
</div>
i use the require function as i'm supposed to, (i think ?!^^) and indicates the folder and retrieve the image name with $(details.image).
As you can see i'm doing a console.log of details image which returns me the filenames without fail.
When i go into the console and check the rendering, i have no issue with the alt, but the src param gives me [object Module]
And that's where i'm kind of lost as to what happens and what i did wrong there.
Thanks by advance

instead of the require module, try importing the image as suggested by creat-react-app docs.
import logo from './logo.jpeg';
import React from 'react';
import logo from './logo.png'; // <<<< image
console.log(logo); // /logo.84287d09.png
function Header() {
// Import result is the URL of your image
return <img src={logo} alt="Logo" />; // <<<<<< Adding to src attribute.
}
export default Header;

Related

Can't find file path of image in reactjs

None of the images I have saved locally can be found when trying to import them in my project.
import {portfolio} from './portfolio.png'
Leads to "Cannot find module './portfolio.png' or its corresponding type declarations.ts(2307)".
The image file path is 100% correct.
Update: Image loads however I would like to know how to remove the typescript error.
Try default import: import portfolio from './portfolio.png'.
Use the ES6 standard to import images into react.
If in public use the absolute path.
If it is in src you can use relative path.
https://create-react-app.dev/docs/adding-images-fonts-and-files/
import MyImage from './logo.svg'; # In local
import MyImage from 'images/logo.svg'; # In Public
export default function App() {
return(
<div>
<img src={MyImage} alt="logo" />
</div>
);
}
Hey #Joe there are multiple ways to call images-
first-
import image from './porfolio.png'
second, in this method you need to post image inside public images folder-
<img src="/images/image.png"/>
Hope these methods help you to solve your query, if you still facing issue just lemme know, I will hlep you.
Thanks

My Image is not rendering in reactjs typescript

I'm creating an app using **reactjs **and **typescript **however I encountered an issue while loading **images **inside a component.
My error in console
Uncaught Error: Cannot find module '../images/test.png'
at webpackEmptyContext...
This is my component:
import { IProject } from '../interfaces/IProject'
import pin from '../svgs/pin.svg'
function Project(props: { project: IProject }) {
const project = props.project
return (
<>
<div className='project'>
<img className='pin' src={pin} alt='pin' />
<div>
<img alt='project gif' src={require(project.image)} />
<span>{project.title}</span>
</div>
</div>
</>
)
}
export default Project
NB : The images are stored inside a 'images' folder and the project component is stored inside a 'components' folder
**NB#2 : **the first image 'pin' loads normally.
Thank you for all the help ~ sorry if this a nooby question.
I tried
replacing (project.image) with ('../images/test.png') and it works if I do that but I want to be able to display the image src passed by the props.
for testing purposes, I added a const projectImage = '../images/test.png and replacing require(project.image) with require(projectImage) and it doesn't work
I created index.d.ts file (according to solutions I found on the internet) and added declare module '*.jpg' and the same thing for jpeg and png. It didn't fix my issue
changing the path of the image
I also installed file-loader
update variable value to contain only the name like this
project.image = 'test.png'
then add the relative path
require(`../images/${project.image}`)

why is local image not showing on browser meanwhile the path is correct in React

The Image am importing from my local Json data that contains the image pathname is not showing on browser and am confused why it not showing. Have use the required tag both on img src and the Json data it self
images: {
mobil: "./images/portfolio/desktop/finshed-next.png",
tablet: "./images/portfolio/tablet/finshed-next.png",
desktop: "./images/portfolio/desktop/color.png",
},
I used both codes below but they dont seem to work
<img src={require(images.desktop)} alt={title} />
<img src={images.desktop} alt={title} />
but if I make an import with the same path, Its working. I mean
import img1 from "./images/portfolio/desktop/color.png",
It will definitely show on the browser.
Hope this should work, if you are using create-react-app.
import React, {useEffect, useState} from 'react';
import './App.css';
function App() {
const [img, setImg] = useState<string>();
const [imgLoc, setImgLoc] = useState<string>();
useEffect(() => {
if (imgLoc !== undefined) {
import(imgLoc).then(image => setImg(image));
}
}, [imgLoc]);
const images = {
mobil: "./images/portfolio/desktop/finshed-next.svg",
tablet: "./images/portfolio/tablet/finshed-next.svg",
desktop: "./images/portfolio/desktop/color.svg",
};
return (
<div className="App">
<h2>Image goes here</h2>
<button onClick={() => setImgLoc(images.mobil)} />
{img && <img src={img}/>}
</div>
);
}
export default App;
I am sorry and if I am wrong, I apologize in advance.
You are probably trying to avoid manually adding the image paths to components. But I can't seem to understand why you would do this.
If the images are dynamic, then in a real-world implementation, they would probably be accessible over a server (statically hosted). In this case, you would receive the src (image URLs) via an HTTP call or something similar. So you won't be importing the images.
... // logic to fetch the list of image URLs
... // logic to render an image tag with an src value being an image URL
But if the images are not changing, then you could probably just import them directly from something like an asset folder as #calimenikk mentioned.

React native: importing Images not working

I have trouble importing image to my component. I saved the images in a filed called WidgetImages and in Images.js I wrote this code to import it:
var Images = {
Weather: require('./WidgetsImages/Weather.png'),
News: require('./WidgetsImages/News.png'),
AgendaWidget: require('./WidgetsImages/AgendaWidget.png'),
SpotifyPlayer: require('./WidgetsImages/SpotifyPlayer.png'),
VoiceReader: require('./WidgetsImages/VoiceReader.png'),
Clock: require('./WidgetsImages/Clock.png'),
};
export default Images;
Then in my component file I have the following:
import Images from '../assets/Images';
// code here ...
<Image source={Images.item} />
I can't figure where the problem is. I looked at previous questions and I have the same structure and my imports are correct. So what seems to be the problem here ?
Can you please past the errors you are getting?
By the code you've pasted, The <Image source={Images.item} /> line must be as below
<Image source={Images.Weather} />
// item should me replaced by the actual properties of the Images object

importing images locally in react

I am not understanding how import works in React. I'm currently using create-react-app. I have a folder inside components folder named images:
- src
- components
- images
Insides the components folder I also have a js file named ProductSquare.js.
I am trying to import a picture from images folder using this line
import bumper from './images/bumper1.png';
I have tried changing it to only bumper1.png and many other options. What am I doing wrong here? ( would appreciate a better way to do it in the future).
Is this how programmers import pictures in the real world?
Try using <img src={require('./images/bumper1.png')} />
P.S.
The similar question goes here
If you are using something like Webpack (which create-react-app does) then yes, you can just import the images (and most other file types). They end up getting converted into something (I believe images end up as a data URL).
If your folder structure looks like this:
src
components
ProductSquare.js
images
Then you should be able to use the image like this:
// in ProductSquare.js
import React from 'react';
import bumper from './images/bumper1.png';
class ProductSquare extends React.Component {
render() {
return <img src={ bumper } />;
}
}
If it isn't, double-check that all of the files are named what you think they should be (check for typos and what not).
If everything is correct and it isn't working, try just adding console.log(bumper) before the class. Then:
if it outputs a string that looks like data:blahblah it should work
if it outputs undefined, the image may not be named properly
if it doesn't output, you might not be using ProductSquare correctly
Using the public Folder
Note: this feature is available with react-scripts#0.5.0 and higher.
Create a folder in public folder, for example, 'image', add your photos there.
After that wherever you want you can use image address like this:
<img className="img1" src="/image/pic.jpg" alt=""/>
You Need to use .default after require
<img src={require('./images/bumper1.png').default} />

Categories