I have sampleposition.png in my assets folder, and a page called myPage.js in my components folder. How do I reference the sampleposition.png in my assets folder from myPage.js. I've tried src="../assets/sampleposition.png" / but that doesn't seem to be working.
If you are using Create React App, the process is fairly easy and straight-forward.
Are you importing it or doing something like <img src="../whatever/>? You need to be importing so that the build will know how to access it at runtime. See Adding Images, Fonts, and Files
import React from 'react';
import logo from './logo.png'; // Tell webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
function Header() {
// Import result is the URL of your image
return <img src={logo} alt="Logo" />;
}
export default Header;
If you aren't, you need to be serving the content statically and referencing the static content address or use a build/bundle tool to put the content into a place that is known ahead of time which is what the create-react-app tool sets up for you.
Import your image and use it in the code. This should do it according to your requirement.
import React from 'react';
import myImage from '../assets/sampleposition.png';
function YourFunction() {
return
<img src={myImage} alt="myImage" />;
}
export default YourFunction;
Related
when I want to export my nextjs app, it says that I cannot export my images on static websites.
Error: Image Optimization using Next.js' default loader is not compatible with next export.
Possible solutions:
- Use next start to run a server, which includes the Image Optimization API.
- Use any provider which supports Image Optimization (like Vercel).
- Configure a third-party loader in next.config.js.
- Use the loader prop for next/image.
How can I make it so that it does ?
Is there a way for me to simply tell it to render images statically ? I dont want to go throught other onlines images loaders..
I created a npm module so that we can use the Next.js <Image/> component with optimized images while using the static export functionality.
https://www.npmjs.com/package/next-image-export-optimizer
The library wraps the <Image /> component of Next.js and automatically creates optimized images using sharp.js at export time.
It uses a custom loader to create a srcset for the <img /> that the <Image /> component of Next.js creates. Then at build/export time, the images inside the public/images folder (as an example) are optimized with sharp.js and copied into the build folder.
You need to set up a custom image loader in Next.js
In your next.config.js file, add this property to the export:
images: {
loader: "custom"
}
And make a script called loader.js that exports this:
function imageLoader({ src }) {
return `/images/${src}`; // REPLACE WITH YOUR IMAGE DIRECTORY
}
module.exports = imageLoader;
For each Image component, set the loader prop manually:
const imageLoader = require("PATH TO loader.js");
<Image loader={imageLoader} />
I'm going to add onto skara9's answer because it didn't quite work for me. I found a thread on github discussing it and the answer there worked for me. It just wraps around the NextJS image component and works pretty flawlessly for me.
// components/Image.js
import NextImage from "next/image";
// opt-out of image optimization, no-op
const customLoader = ({ src }) => {
return src
}
export default function Image(props) {
return (
<NextImage
{...props}
loader={customLoader}
/>
);
}
Make sure you change your imports and update your next.config.js
import Image from '../components/Image.js'
This is my folder hierarchy-
SRC -
/assets
/components
App.jsx
COMPONENTS -
/screens/Login.jsx
Carousel.jsx
Navbar.jsx
Suppose I am in the Login.jsx file. From there how will I import a context which was declared in App.jsx
When I start writing this code -
import React from 'react';
import { IsLoggedInContext } from '../'
The autocompletes in vscode editor I get are -
Carousel
Navbar
Screens
When I start using .../ no autocomplete comes for the App file and it doesn't also work if I manually write this code -
import { isLoggedInContext } from '.../App'
So, how will I import the context in the Login.jsx file? Is there any way?
A single . is the current directory, a double .. is the parent directory. A triple ... isn't valid syntax for referencing directory/file structures.
From src/components/screens, ".." gets you into src/components, and "../.." gets you up another level back to src.
import { isLoggedInContext } from '../../App';
I'm creating a react app. I have an image folder with a few files. In order for React to render the image I have to import it like I import other modules. Something like this:
What I want to do is import the whole image folder, and then find a way to access each file in my Component. for example:
import img from '.../img'
In my JSX, I want to be able to access each of the files from the imported image folder.
Is it possible to do?
You still need to import those images in some place. For cleaner syntax in your main component file, I will group the image files in 1 file
//grouping images in one module. Let's say it is image.js
import imageA from <your-patha>
import imageB from <your-pathb>
import imageC from <your-pathc>
export default {
imgA: imageA,
imgB: imageB,
imgC: imageC
}
//Home component
import Images from '<image.js path>'
const Home = () => {
return (
<img src={Images.imgA} //...other props />
)
}
The best way to do this is you can put all your images in the public folder and refer like below on component.
<img src="/image.jpg" alt="image" />
I have an issue regarding a link not loading my image when I pass a prop to the attribute src of img. I have tried wrapping require() around my links and it didn't work.
I have a huge library of products which would be unfeasible to manually import images using the image loader.
Therefore, is there a way to load an image using props inside the src attribute?
I am using NODE_PATH=src/
Thanks for the help!
export const productLib = [{
ID: "001",
name:"product name",
src: "lib/productLib/img/product_name",
color: "",
...
}, {...}]
import React from 'react';
export class Products extends React.Component {
render() {
return(
<div className="products">
<img src={this.props.product.src} width="50" />
<h6>{this.props.product.name}<span className={`block ${this.props.product.color}`}></span></h6>
</div>
)
}
}
As recommended by Xuscrus, I linked my images using the public path. I had to remove my absolute path in order for this solution to work.
I moved all of my images inside a folder named "img" inside the public folder of my create-react-app.
With the example used in my initial statement, here is the easiest solution I found:
import React from 'react';
export class Products extends React.Component {
render() {
return(
<div className="products">
<img src={`/img/${this.props.product.src}.png`} width="50" />
<h6>{this.props.product.name}<span className={`block ${this.props.product.color}`}></span></h6>
</div>
)
}
}
My main reference for my solution was this post (URL method in the correct answer) :
How to do Dynamic images in ReactJS?
I think issue is related with the way you are sending the url to the component.
"lib/productLib/img/product_name" is not an url, not relative url also.
You can use import to get the image.
import React from 'react';
import logo from './logo.png'; // Tell webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
function Header() {
// Import result is the URL of your image
return <img src={logo} alt="Logo" />;
}
export default Header;
If you are using react-create app
they resolve the problem for you:
https://create-react-app.dev/docs/adding-images-fonts-and-files/
I came across a similar issue in fact I was searching for the solution at the moment but figured it out myself I have Images store in a separate folder and I'm importing them in the data file and then Passing it to the component where I needed it, but the image was not displaying.
All I did was
//img is the variable I'm getting the image path at
console.log(img)
That returned
Module {default: "/static/media/svg-1.af890272.svg", __esModule: true,
Symbol(Symbol.toStringTag): "Module"}
default: "/static/media/svg-1.af890272.svg"
Symbol(Symbol.toStringTag): "Module"
__esModule: true
[[Prototype]]: Object
After Getting this in the Module Object I saw the default value so just do
img = img.default
And now you can pass it in src
import React from 'react';
<img src={img} width="50" />
I am adding multiple images in my web page by placing each image in same directory that of components (see screenshot) How can I place the image files in another folder and then access them inside my components.
content.js:
import React, { Component } from 'react';
import java from './java.png';
import neural from './neural.png';
import future from './future.gif';
import neuralnet from './neuralnet.jpg';
import dsa from './dsa.png';
import dl from './dl.jpg';
import ml from './ml.jpg';
import python from './python.png';
import ai from './ai.jpg';
<img className="futuregif" src={future} alt="gif" height="240" width="320"></img>
<img className="javacardimg" src={java} alt="Java" height="65" width="65"></img>
<img className="neuralcardimg" src={neural} alt="neural" height="65" width="65"></img>
and so on.. for all other images
Components and image files are getting mixed together is there any other specific way to do it by making a image folder but then what should be the path in src="".
File structure:
To clarify my comment.
Create a directory assets containing all your assets like images.
Then import the right path and load your content like:
import neural from './assets/images/neural.png';
class myComponent extends Component {
render() {
return (<div><img src={neural} alt=""/></div>);
}
}
In my point of view you can create a js file and export const imageName. in const you can specify your image path.
constant.js
import React from 'react';
import java from './java.png';
export const javaImg = java;
Then in your component file you need to import that js file and you can use those const according to your requirement.
Component
import constant from './constant';
class x extends Component {
constructor(props) {
super(props);
console.log(constant.javaImg);
}
}
export default x;
If you are importing images in same component it'll work but the component will become a lengthy and complex looking.
so my suggestion is like this.