importing images locally in react - javascript

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} />

Related

Run async code in nextjs component without using UseEffect

In my nextjs app, I have a StrapiImage component that accepts an image object from my strapi backend api as a prop. It assigns the width, height and url + any aditional props. (It's basically a shortcut for a regular next/image)
import Image from "next/image";
import { getStrapiMedia } from "../../lib/media";
export default function StrapiImage({ image, ...props })
return <Image src={getStrapiMedia(image)} // the getStrapiMedia function basically just returns the url to the image.
width={image.attributes.width}
height={image.attributes.height}
alt=""
{...props} />
}
Now, I wanted to add a blur placeholder for this image using placeholder="blur" but since this is an external image, I have to provided a base64 image in the blurDataUrl prop.
I wanted to generate an image like this with the plaiceholder library similarly to this sollution I found.
There's a problem with this though, to generate the image, I need to use an await statement. In getStaticProps, this wouldn't be a problem as I could just make the function async, but I'm doing this inside a component and components must regular non-async functions.
The 'obvious' sollution would be to use the useEffect hook like so:
import Image from "next/image";
import { getStrapiMedia } from "../../lib/media";
import { useEffect, useState } from "react";
import { getPlaiceholder } from "plaiceholder";
export default function StrapiImage({ image, ...props })
const [blur64, setBlur64]
useEffect(() => {
async function generatePlaceholder() {
// generate base64 image here
}
generatePlaceholder();
}, [])
return <Image src={getStrapiMedia(image)}
width={image.attributes.width}
height={image.attributes.height}
alt=""
placeholder="blur"
blurDataURL={blur64}
{...props} />
}
This would technically work, but it would only run only on the client-side, ultimately defeating the purpose of ssr and the whole image optimisation. (Especially considering plaiceholder's huge js bundle)
Is there any other way that I could do this without useEffect but still in the component file? Ideally, I'd like it to run only on the server-side.
I'm using nextjs#13
I fixed the issue by using a strapi plugin to generate the placeholder image on the backend rather than on the frontend.
The issue in the title still remains unsolved though. Running pre-renderable async code at component-level doesn't seem to be officialy supported by nextjs. (with the pages directory)
Here's some "sollutions" I've found: (mostly workarounds)
Generate the placeholders on page-level. For me, that would mean looping through all elements in my api data looking for images and generating placeholders for them. It's pretty inconvenient but it does work.
Switch to the app directory. (provided you're using next 13) It uses react server components so all of this is possible and simple to do there.
Try to work with useSSE. I haven't looked into this too much but it looks like you can use the useSSE library to run server-side at component-level. Here's an article covering this.

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 img path works but not with path.join?

Using React 16.13.1, I have the follow class:
import React from "react";
const path = require('path');
class Portrait extends React.Component {
render() {
const vikingName = this.props.name.toLowerCase(); // Expected output of "ulf"
return (
<div>
// below img tags go here
</div>
)
}
}
export default Portrait
I'm trying to have a the src prop of the img tags be dynamic, so when the parent component calls it, it passes the name of the viking. The file directory is name-spaced.
This works:
<img src={require('../../../../res/img/ulf/picture.png') />
Error: "Module not found at '../../../../res/img/ulf/picture.png'
<img src={require(path.join('../../../../res/img', vikingName, 'picture.png'))} />
Error: "Module not found at '../../../../res/img/ulf/picture.png'
<img src={require(`../../../../res/img/${vikingName}/picture.png`)} />
When this.props is loading correctly, (this.props.name gives expected output) and all types are String and print the correct, same path, why do the bottom two do not work?
The problem isn't your code itself. The problem lays a little deeper in how Webpack bundles your code.
Webpack bundles your code and assets and creates an entirely new folder structure and/or filenames.
Webpack will turn a folder structure like this:
src
- app.jsx
- components
- - MyComponent.jsx
- assets
- - image.jpg
into:
dist
- main.js
- image.jpg
The whole point about imports/exports is that they are static. Webpack will change all your paths behind the scenes to point towards the newly created bundled path during it's bundling process. That's why your first example works smoothly. That path has been defined before runtime, so before webpack bundles your code.
However...
Dynamic imports which are updated at runtime point towards a path which doesn't exist in your bundled code. That's why it throws an error that it can't find your file. Because there simply is no such file at that location in your bundled code.
Luckily there is a workaround for this issue
How to solve this:
It's possible to access the files path relative to your bundle using require.context. This allows you to parse your relative path to the bundled path and dynamically update your images.
This answer should be able to set you on your way.

ReactJS and images in public folder

Im new in ReactJS and I want to import images in a component. These images are inside of the public folder and I do not know how to access the folder from the react component.
Any ideas ?
EDIT
I want to import an image inside Bottom.js or Header.js
The structure folder is:
I do not use webpack. Should I ?
Edit 2
I want to use webpack for loading the images and the rest of assets. So in my config folder I have the next files:
Where I need to add the paths of the images and how?
Thanks
You don't need any webpack configuration for this.
In your component just give image path. React will know its in public directory.
<img src="/image.jpg" alt="image" />
To reference images in public there are two ways I know how to do it straight forward.
One is like above from Homam Bahrani.
using
<img src={process.env.PUBLIC_URL + '/yourPathHere.jpg'} />
And since this works you really don't need anything else but, this also works...
<img src={window.location.origin + '/yourPathHere.jpg'} />
the react docs explain this nicely in the documentation, you have to use process.env.PUBLIC_URL with images placed in the public folder. See here for more info
return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
1- It's good if you use webpack for configurations but you can simply use image path and react will find out that that it's in public directory.
<img src="/image.jpg">
2- If you want to use webpack which is a standard practice in React.
You can use these rules in your webpack.config.dev.js file.
module: {
rules: [
{
test: /\.(jpe?g|gif|png|svg)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 10000
}
}
]
}
],
},
then you can import image file in react components and use it.
import image from '../../public/images/logofooter.png'
<img src={image}/>
Create a folder in public ex.Assets and put your image in that folder and assign the folder_name / image_name in src
<img src = "/Assets/cardimg.svg" alt="Card image cap" width="400" />
We know React is SPA. Everything is rendered from the root component by
expanding to appropriate HTML from JSX.
So it does not matter where you want to use the images. Best practice is to use an absolute path (with reference to public). Do not worry about relative
paths.
In your case, this should work everywhere:
"./images/logofooter.png"
Simply Use
<img src='/image.extension' />
React will automatically point toward the public directory
You should use webpack here to make your life easier. Add below rule in your config:
const srcPath = path.join(__dirname, '..', 'publicfolder')
const rules = []
const includePaths = [
srcPath
]
// handle images
rules.push({
test: /\.(png|gif|jpe?g|svg|ico)$/,
include: includePaths,
use: [{
loader: 'file-loader',
options: {
name: 'images/[name]-[hash].[ext]'
}
}
After this, you can simply import the images into your react components:
import myImage from 'publicfolder/images/Image1.png'
Use myImage like below:
<div><img src={myImage}/></div>
or if the image is imported into local state of component
<div><img src={this.state.myImage}/></div>
Try This One its easy and Simple
Don't Make Image folder in src.
Make an image folder in public.
you work in react-bootstrap install
npm install react-bootstrap
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Image } from 'react-bootstrap';
export default function Main() {
return (
<>
<Image src="/img/image.jpg/100px250" alt="bg image" fluid />
</>
)
}
Hope it's Done
here is sure and three simple way to do that...
you can make one folder in directory and access it as we do import way or
you can give direct image name in src
<img src="image__name" alt="yourpic" />
//by default react look in public folder can render image in img tag
const image = window.location.origin + "/image.png";
// if your image in public directory inside folder imagecollection than you can import it in this way
const image = window.location.origin + "/imagecollection /image.png";
<img src={image} alt="yourpic" />
A simple solution is to use paths like this /images/logoFooter.png. If the file is located directly under the public folder, do /someImage.png. You can go deeper, /x/y/z/image.png. Treat the locating part of the image as an absolute kind of location for that image.
For more information, check out https://create-react-app.dev/docs/using-the-public-folder/.
if you want to add your javascript file from public folder to react, put specific file to index.html file in public folder. Your problem will be solve.
You Could also use this.. it works assuming 'yourimage.jpg' is in your public folder.
<img src={'./yourimage.jpg'}/>

Categories