I am trying to display the data and image using a component.First time the data and images appears but when i refresh the page then data and images both disappear.
This is by component Team.js
import React from 'react';
const Team = (props)=>{
return(
<>
<h1>{props.data.name}</h1>
<img name="photo" src={require(`../images/${props.data.image}`)}/>
</>
)
}
export default Team;
My component is present in components folder and images are present in images folder.
require usually does not work with string literals (template strings). In other words, the location needs to be known at compile time.
I see two solutions.
1. Store your images in the public/images folder, and reference them using your website URL (Preferable)
Lets say you store all your image in the public/images folder. We can get the public url of the website using
var imageBasePath = window.location.protocol + "//" + window.location.host + "/images/";
this will then allow us to use this to reference our public images in the src for an img tag.
<img name="photo" src={imageBasePath + props.data.image} />
where image is the actual name of the image located in the public/images folder.
your team component would look like this
const Team = (props) => {
var imageBasePath =
window.location.protocol + "//" + window.location.host + "/images/";
return (
<>
<h1>{props.data.name}</h1>
<img name="photo" src={imageBasePath + props.data.image} />
</>
);
};
2. Store required images in an array and reference by index, export as an object.
Probably not the preferable method, as working with indexes can be tricky.
export const imageList = [
require("./checklist.jpg"),
require("./question.jpg"),
require("./test-pattern.jpg")
];
and then the Team implementation
import { imageList } from "./Images/imageList";
export const TeamRequire = (props) => {
let image = imageList[props.data.id];
return (
<>
<h1>{props.data.name}</h1>
<img name="photo" src={image} />
</>
);
};
to ease the index issue, we can store and fetch them by objectKey instead
export const imageListObj = {
checkList: require("./checklist.jpg"),
question: require("./question.jpg"),
testPattern: require("./test-pattern.jpg")
};
import { imageListObj } from "./Images/imageList";
export const TeamRequireObj = (props) => {
let image = imageListObj[props.data.imageId];
return (
<>
<h1>{props.data.name}</h1>
<img name="photo" src={image} />
</>
);
};
Here is a codesandbox with the three concepts.
https://codesandbox.io/s/adoring-rosalind-2xhj67?file=/src/App.js
Related
I am trying to get the data from Api (azureMsal). I used one of the library to create image slide show (simpleImageSlider)
The library take the images from array that defined as Images
const images = [
{ url: "https://qxpy.sharepoint.com/sites/AlbaportalTEST/Lists/Picture%20Slider/Attachments/2/337Slider01.jpg" },
];
What I am trying to do is when Azure bring the link for the photo save the photo into (images) Array
import React, { useState, useEffect } from "react";
import SimpleImageSlider from "react-simple-image-slider";
export function PannelPhoto(info) {
console.log("this data used😍",info)
//const test = info.graphData.value;
const images = [
{ url: "https://qxpy.sharepoint.com/sites/AlbaportalTEST/Lists/Picture%20Slider/Attachments/2/337Slider01.jpg" },
];
return (
<div>
{info?.info?.value?.map((slideImage, index)=> (
<div key={index}>
</div>
))}
<SimpleImageSlider
width={830}
height={341}
images={images}
showBullets={true}
showNavs={true}
/>
</div>
);
}
This is the full code
I tried to assign slideImage.fields.ImageLink into <image> tag
I am trying to dynamically get images from my images folder based on some information retrieved from the database. Gone through as many resources as I could but still unable to solve the problem. Here's my code:
import scimitar from "../../images/scimitar.png";
import defender from "../../images/defender.png";
import arrows from "../../images/arrows.png";
import cape from "../../images/cape.png";
import platebody from "../../images/platebody.png";
const ItemCard = ({ item }) => {
return (
<div>
<p key={item.id}>ID: {item.id}</p>
<p>Name: {item.name}</p>
<p>{item.examine}</p>
<p>
<Link to={`/items/${item.id}`}>{item.name}</Link>
</p>
<img src={require(item.name)} alt={item.examine} />
</div>
)
}
const ItemList = () => {
const [items, setItems] = useState(null);
const populateItems = async () => {
const data = await getItems();
setItems(data);
};
useEffect(() => populateItems(), []);
return (
<div>
{items &&
items.map((item, index) => (
<ItemCard item={item} key={index} />
))
}
</div>
)
}
It looks like there are a couple of issues going on. Using template literals like
<img src={`../../images/${item.name}.png`} alt={item.examine} />
won't work either. The reason why is src doesn't take in a path to picture, it looks at a url your website uses. You'll need to setup your React app to serve public images (e.g. make sure something like localhost:1337/images/schimitar.png works).
Only then can you reference it using
<img src={`/images/${item.name}.png` />
To serve static files in create-react-app check out this link. If you have another setup you'll need to use something like babel-plugin-file-loader to serve public assets.
Not sure why this worked but I placed the path of the image in a variable before passing it to the src path of the image tag.
const ItemCard = ({ item }) => {
const imageItem = `/images/${item.name}.png`;
return (
<div>
<p key={item.id}>ID: {item.id}</p>
<p>Name: {item.name}</p>
<p>{item.examine}</p>
<span>Quantity: {item.quantity}</span>
<p>
<Link to={`/items/${item.id}`}>{item.name}</Link>
</p>
<img src={imageItem} alt={item.examine} />
</div>
)
}
export default ItemCard;
<img src={item.name} alt={item.examine} />
Try the following code if you are trying to get the image from a static path.
import image1 from 'images/image1.png';
<img src={image1} alt="image1" />
If you are trying to dynamically add the image then try the following code,
const imgName = "image1.png"
return (
<div>
{ imgName && <img src={`images/${imgName}`} alt="imgName" /> }
</div>
)
My Next.js app's pages are provided by an API, each with a uri_prefix and a uri.
The uri_prefix is mandatory, and can be c or s for now. But any letter could be chosen in the end.
It's a pretty simple structure :
pages
|-[prefix]
| |
| |-[slug]
The [slug].jsx page that handles it uses ISG.
So far, the getStaticPath fallback was set to true, so that if an admin creates new pages (eg. {uri_prefix : c, uri : newpage1} & {uri_prefix : s, uri : newpage2}) in the backoffice, ISG generates the static /c/newpage1 and /s/newpage2 file when they are first triggered.
But once generated, trying alt url such as /x/newpage or /whatever/newpage also fires up the page, which is somewhat unexpected (and unwanted). Reading the doc, I thought it would allow only existing prefixes.
Setting fallback to false forbids unwanted urls but also requires a new build of the app, which is not convenient.
I'd like to have /c/newpage1 or /s/newpage2 rendered, but not /c/newpage2 nor /s/newpage1 (nor /somethingelse/newpage* of course). Each page associated with it's own prefix only.
Did I misunderstood how the fallback works ?
Is ther an obvious mistake in the code or is there another way to achieve ISG for new pages without whole build while forbidding unwanted urls ?
Here is the [slug].jsx page :
import Layout from '#/components/Layout';
import SmallCard from '#/components/SmallCard';
import {useRouter} from 'next/router';
export default function src({products, seo}) {
const router = useRouter();
if(router.isFallback) {
return (
<h1>Loading new page...</h1>
)
}
return (
products ? (
<Layout title={seo[0].title} description={seo[0].description}>
<div>
<div className='container-fluid my-5'>
<div className="row justify-content-center">
<h1>{seo[0].h1}</h1>
</div>
<div className="row justify-content-center">
{products.map(
(product)=>(
<SmallCard product = {product}/>
)
)}
</div>
</div>
</div>
</Layout>
) : (
<Layout title={seo[0].title} description={seo[0].description}>
<h1>{seo[0].h1}</h1>
<div dangerouslySetInnerHTML={{__html: seo[0].content_front}}/>
</Layout>
)
)
}
export async function getStaticPaths() {
const resPages = await fetch(`${process.env.API_BASE_URL}/path/to/pagesapi`);
const pages = await resPages.json();
const paths = pages.map((page) => ({
params: {
prefix: page.uri_prefix,
slug: page.uri
},
}))
return {
paths,
fallback: true
};
}
export async function getStaticProps({ params: { slug } }) {
const resPages = await fetch(`${process.env.API_BASE_URL}/path/to/pagesapi`);
const pages = await resPages.json();
const seo=pages.filter(page=> page.uri == slug);
if(seo[0].src) {
const src=seo[0].src;
// get products
const resProducts = await fetch(`${process.env.API_BASE_URL_LEGACY}${src}`);
var products = await resProducts.json();
} else {
var products = null
}
return {
props: {
products,
seo
},
revalidate:60,
};
}
Thanks in advance.
Basically, in my use case, I'm receiving File Object from Parent to the Download component through the props and I want to be able to straight away download it. Is there a way I can do that ?
Please find below reference. [I know, it looks a bit weird in Parent component to select file using file input and to be able to download it just then. This is just for the sake of simplicity.]
Download Button
const DocumentMessage = ({file, type, label, ...props}) => {
return (
<Button as='a' style={{textDecoration: 'none'}} target='_blank' href={file} {...props}>{label}</Button>
);
}
Example of Parent Component where it's used -
export const documentMessageDefault = () => {
const [selectedFile, setSelectedFile] = useState(null);
const handleFileChange = (e) => {
file = e.target.files[0];
setSelectedFile(file);
}
return (
<div>
<input type='file' onChange={handleFileChange} />
<DocumentMessage file={selectedFile} label= 'Download File' />
</div>
);
}
I have an app that displays images from an API.
However some of the items don't have the required backdrop_path.
How would I display a different image if the original is not available
Here's my code
const MovieItem = ({ movie }) => {
const imagePath = 'https://image.tmdb.org/t/p/w500';
return (
<img src={`${imagePath}${movie.backdrop_path}`} alt={movie.title} />
I want the img to be {movie.poster_path} but only if {movie.backdrop_path} is null or not existent.
Or alternatively a hard coded image to display instead.
here's an answer for React, using a ref to allow the component to modify the image's source if it errors (i.e. the image specified by prop 'src' doesn't exist). In this example the fallback image is hard-coded, but could also be a prop etc.
import { useRef } from 'react';
const imageWithFallback = ({ src }) => {
const imgRef = useRef();
const onImageError = () => imgRef.current.src="/fallback-image.png";
return (
<img ref={imgRef} src={src} onError={onImageError} />
)
}
you can try use img's onerror event, it will be fired when it failed to load the resource.
You can use conditionally paths like this:
const MovieItem = ({ movie }) => {
const imagePath = 'https://image.tmdb.org/t/p/w500';
const src = ${movie.backdrop_path} === null || ${movie.backdrop_path} ===
undefined ? {movie.poster_path} : ${movie.backdrop_path}
return <img src={src} alt={movie.title} />
}
<img src={`${imagePath}${movie.backdrop_path || movie.poster_path}`} alt={movie.title} />
You can use conditional statements for images.