Module not found in react for render image from api - javascript

I currently creating a react app of e-commerce, I am stuck with a feature where when the product clicks and redirects to the product details page, I successfully can get the product image and the details using props but can't get the product image. The product image needs a call from an API. So I try to direct call from the src. But I getting the error of the Module not being found. Plz, help me with this.
Getting an error in the code in this line where I try to call the API directly tp src.
This is the error I'm getting
// carousel items
const carouselItems = [
{
src: require(`/api/v1/ProductFile/${encodeURIComponent(
data.data.ID
)}/Product/${encodeURIComponent(
data.data.ProductImages[0]
)}`),
altText: "Somewhere",
caption: "Somewhere",
},
{
src: require("assets/img/megan-product-2.jpg"),
altText: "Somewhere else",
caption: "Somewhere else",
},
{
src: require("assets/img/megan-product-3.jpg"),
altText: "Here it is",
caption: "Here it is",
},
{
src: require("assets/img/megan-product-4.jpg"),
altText: "Here it is",
caption: "Here it is",
},
];
<div>
<Row>
<Col key={data.data.ID} md="7" sm="6">
<div className="ml-auto mr-auto" id="carousel">
<Card className="page-carousel">
<Carousel
activeIndex={activeIndex}
next={next}
previous={previous}
>
<CarouselIndicators
items={carouselItems}
activeIndex={activeIndex}
onClickHandler={goToIndex}
/>
{carouselItems.map((item) => (
<CarouselItem
onExiting={onExiting}
onExited={onExited}
key={item.src}
>
<img src={item.src} alt={data.data.Name} />
<CarouselCaption captionHeader={data.data.Name} />
</CarouselItem>
))}
</Carousel>
</Card>
</div>
{/* end carousel */}
</Col>
</Row>
</div>

thanks, I have solved it by just remove the require word.

You should remove require() wrapping the API URL.
The error is telling you that the file path does not exist.
Each item in the Carousel uses an <img> that takes an src attribute. To use an API endpoint/URL for the src, it should be passed directly as a string without using require.

Related

Attribute is not saved in Gutenberg

I am trying to create a custom block for Wordpress Gutenberg.
I have the following attributes:
"icon": {
"type": "object",
"source": "html",
"selector": ".jig_defbox-icon"
},
"color": {
"type": "string",
"default": "#919191"
}
In my EditJS I try to store values from a color-picker and a radiogroup into these attributes.
const [ toggled, setToggled ] = useState( );
return(
<InspectorControls>
<ColorPalette
colors={[
{name: 'lightgray', color: '#d8d8d8'},
{name: 'darkgray', color: '#919191'},
{name: 'red', color: '#dc1a22'}
]}
disableCustomColors={true}
onChange={(value) => {props.setAttributes({color: value});}}
value={props.attributes.color}
clearable={false}
/>
<RadioGroup
onChange={ (value) => {setToggled(value);props.setAttributes({icon: value});} }
checked={props.attributes.icon}
>
{
str_array.map(
item => ( <Radio value={item}><Icon icon={icon_getter(item);}/></Radio>)
)
}
</RadioGroup>
</InspectorControls>
)
In my SaveJS I try to render my markup according to these attributes:
const {attributes} = props
<div style={{"fill": attributes.color}}>
<Icon icon={icon_getter(attributes.icon)}/>
</div>
The goal is to render an svg-icon according to the selection on my radiogroup.
Issue 1: Every new edit-session in backend, the selection of my radiogroup is gone, even with useState (tried without useState first)
Issue 2: Every new edit-session, a console error is logged, that says that the post-body markup does not match the markup returned by the save function, because the save-markup does not contain the icon attribute content
As far as I was able to enclose the problem, the icon attribute is not correctly saved. I tried to save the "key" for the icon as a string and object. If I log the value in the save function, it is empty, while the selected color works as expected, both in frontend and backend.
I was able to fix it via rethinking my concept of fetching the icon.
Apparently, Gutenberg tried to store the code of the icon into the database, but not the key. When loading the backend editor, the icon_getter function received a null value, therefore, the difference between post body and save function code.
I changed my editJS:
<RadioGroup
onChange={ (value) => {props.setAttributes({icon: value});} }
checked={props.attributes.icon}
>
{
my_icons_as_list.map(
item => ( <Radio value={item}><Icon icon={my_icons[props.attributes.icon];}/></Radio>)
)
}
</RadioGroup>
and my saveJS:
<Icon icon={ my_icons[ attributes.icon ] } />

Image not appearing in .map

I have a map that displays data from an array in another jsx file.
{data.map((nftDetail) => {
return (
<div className="card" key={nftDetail.id}>
<img src={nftDetail.img} alt="" />
<h3>{nftDetail.title}</h3>
<h4>{nftDetail.owner}</h4>
<h5>{nftDetail.category}</h5>
</div>
);
})}
Data example :
{
id: 1,
title: "#247",
category: "Top",
owner:"c568c3",
img:"../../assets/1.png"
},
The image is not appearing (everything else is displayed)
Screenshot
Do i need to import something else? Why is the photo not appearing? Thanks!
./1.png - does this path contain the image can you check that and use a correct path reference for the image

How to exclude certain item in a map with a certain condition?

I'm developing a menu page, where users can see the menu's items based on their roles.
Currently, I have 3 pages: Bulletin Board, Info Hub and Settings
So naturally, I have 3 roles: Admin Role (can access all 3 of the pages), Bulletin Board (can only access Bulletin Board), Info Hub (can only access Info Hub)
So users can have a different roles, for example, if they have Bulletin Board and Info Hub, then they can access both of them, but not the Settings page (only "Admin Role" can see Settings), so I want to hide the Settings in this menu that I've already developed and rendered using map.
Or if the user has all 3 roles including Admin Role, then they can see everything as well.
I'm taking the loginList prop from an API and passing it into the AllAppsCentre.js to determine which menu items to show, but I just can't figure out the logic to do a filter or indexOf at the map.
In the codesandbox that I've created, the user has all 3 roles.
AllAppsCentre.js(map function to display the menu items)
useEffect(() => {
const loginListFromParent = loginList;
const showAll = loginListFromParent.some(
(item) =>
item.permissionName.includes("Admin Role") &&
item.permissionType.includes("view")
);
const showBulletin = loginListFromParent.some(
(item) =>
item.permissionName.includes("Bulletin Board") &&
item.permissionType.includes("view")
);
const showInfoHub = loginListFromParent.some(
(item) =>
item.permissionName.includes("Info Hub") &&
item.permissionType.includes("view")
);
if (loginListFromParent) {
setShowAll(showAll);
setShowBulletin(showBulletin);
setShowInfoHub(showInfoHub);
}
}, [loginList]);
return (
{AllAppsCentreData
.filter((item) => {
.map((item, index) => {
return (
<Col key={index} xs={6} md={3}>
<div className={item.className}>
<Link to={item.path}>
{item.icon}
<Row>
<span className='apps-title'>
{item.title}
</span>
</Row>
</Link>
</div>
</Col>
)
})}
)
AllAppsCentreData.js
import * as IoIcons from 'react-icons/io'
import * as MdIcons from 'react-icons/md'
export const AllAppsCentreData = [
{
title: 'Bulletin Board',
path: '/bulletinboard',
icon: <IoIcons.IoIosPaper size={80} />,
className: 'row text-center apps-centre-icon'
},
{
title: 'Info Hub',
path: '/infohub',
icon: <MdIcons.MdDeviceHub size={80} />,
className: 'row text-center apps-centre-icon'
},
{
title: 'Settings',
path: '/settings',
icon: <IoIcons.IoMdSettings size={80} />,
className: 'row text-center apps-centre-icon'
},
]
I've been trying to figure out how to deal with this but I just couldn't think of a solution, if all else fails, I might just remove the map method and just copy and paste my AllAppsCentreData's items and move it directly into the AllAppsCentre page instead so I can do ternary operations at the menu items.
If there is any better way to do this menu with the role-based display, feel free to let me know as I also want to learn the optimal way to do something like this.
To start off, there is no variable in your code that is responsible for holding current user's permissions (or I can't see one). So I made it up:
const currentUsersPermissions = useGetPermissions() // get users permissions
// the above can be "admin", "bulletin" or "info-hub"
Then, you need to first filter your array and then map it (currently, you are using map inside of filter). To do it easier and correctly, you could add a property called requiredPermission (or something simillar) to your AllAppsCentreData objects:
{
title: 'Bulletin Board',
path: '/bulletinboard',
icon: <IoIcons.IoIosPaper size={80} />,
className: 'row text-center apps-centre-icon',
requiredPermission: "bulletin" // and info-hub for Info Hub
},
Then, while rendering and mapping, you can do it like this:
return (
{AllAppsCentreData
.filter(
// below, you return true if permission is admin because he can see everything
// and true or false depending if permissions are other than that but
// the same as required by AllAppsCentreData array objects
(item) => currentUsersPermissions === "admin" ? true : currentUsersPermissions === item.requiredPermission
).map((item, index) => {
return (
<Col key={index} xs={6} md={3}>
<div className={item.className}>
<Link to={item.path}>
{item.icon}
<Row>
<span className='apps-title'>
{item.title}
</span>
</Row>
</Link>
</div>
</Col>
)
)
So, to sum up:
I have created a variable to hold current users' permission
I have added a property to each AllAppsCentreData's objects, which contains info about permission required to show it
I have filtered the array right before mapping it and rendering, so it contains only the data I want to render
Also, I think you are lost in using filter method, so perhaps read this and try doing some easier excercises to get a feeling how it works: MDN on Array.filter method. The thing you need to pay attention is that you pass a function into filter, and this function should return true or false depending on whether you want your item included in the output array.

Imported image showing image path instead of the image - React.js

I tried importing an image but instead of displaying the image, it's displaying the path to the image instead.
The Array I'm creating, and I'm still adding more data to it is:
import importedImage from './assets/path.png';
export const membersData = {
All: [
{
id: 1,
picture: importedImage,
name: 'Demo name',
location: 'Demo location',
role: 'Consultant ',
contact: 'T: number \nE: mail'
},
],
}
How I rendered it:
{posts.length === 0 ? (
<p>No posts...</p>
) : (
posts.map((post) => (
<div key={post.id}>
{post.picture}
</div>
)))}
result : /static/media/path.aba65f86.png
Note: The path isn't what I've actually used, it's just for demonstration purposes
if your bundler configured well, with import you should get a base64 image url.
So you can just pass it to the img tag:
<img src={post.picture} alt=""/>
Pass the Imported Image url to the image tag's src attribute.
<img src={post.picture} alt="Could not load image" />

Nested Image Array Fails to Load

I'm relatively new to react and javascript (I'm usually backend Java). I'm currently trying to make an image gallery, where the subsections are clicked on and thumbnails of the images within each section are displayed. The thumbnails can then be clicked on and open a lightbox (I'm utilizing simple-react-lightbox for this and am on the latest version).
It works, but inconsistently. Sometimes when I click on the thumbnail, instead of throwing up the lightbox and being able to click through the images, it takes me directly to the full sized image.
My nested array with the image data, (imports of images omitted)
const GALLERIES =[
{
name: 'Beaded Jewelry',
id: 'beadwork',
description: 'placeholder',
resources:[
{
id: 1,
thumbnail: bluependant,
url: blue,
title: 'Blue Swarovski Pendant'
},
{
id: 2,
thumbnail: greenpendant,
url:green,
title: 'Green Swarovski Pendant'
}
]
},
{
name: 'Wire Jewelry',
id: 'wirewrapped',
description: 'placeholder #2',
resources:[
{
id: 'wire1',
thumbnail: wire1Thumb,
url: wireWrap1,
title: 'placholder 1'
},
{
id: 'wire2',
thumbnail: wire2Thumb,
url:wireWrap2,
title: 'placholder 1'
}
]
}
];
export default GALLERIES
And the js that I'm trying to make work consistently.
import React from 'react';
import '../css/gallery.css';
import '../css/jewelry_main.css';
import GALLERIES from '../data/galleries';
import SimpleReactLightbox from "simple-react-lightbox";
import { SRLWrapper } from "simple-react-lightbox";
import {Link } from 'react-router-dom';
const Gallery = props =>{
const{thumbnail, url, title } = props.subgallery;
return(
<div className="gallery">
<a href={url} data-attribute="SRL">
<img src={thumbnail} alt={title} />
</a>
</div>
)
}
const JewelryGallery = ({match}) =>{
const gallery = GALLERIES.find(({ id }) => id === match.params.keyword)
return(
<div>
<div className="frosted">
<p>{gallery.description}</p>
</div>
<SimpleReactLightbox>
<SRLWrapper>
{
gallery.resources.map((SUBGALLERY) =>{
return(
<Gallery key = {SUBGALLERY.id} subgallery={SUBGALLERY} />
)
})
}
</SRLWrapper>
</SimpleReactLightbox>
</div>
);
}
export default JewelryGallery;
Any insight or wisdom would be greatly appreciated! Thank you!
UPDATE EDIT: I noticed something, the first subgallery I click into will always present with the lightbox, but the second one, consistently fails and instead goes directly to the fullsize of whichever image I have clicked on. (It doesn't matter which of the two I pick first, the second always fails.) But I can't discern why the lightbox would not get applied to the second gallery I select.
There are only two things I can see that differ from the documentation for the simple-react-lightbox package.
First thing is, with the latest version, you only need to use the <SRLWrapper> component. You have both the <SRLWrapper> and the <SimpleReactLightbox> component in use. Perhaps try getting rid of the old version if you have the latest version of the package installed.
Second thing is the structure of your Gallery component return has the div wrapping the elements. I'm not sure if this would cause any problems but, to get as close as possible to the example in the docs you could try using a fragment instead of a div.
const{thumbnail, url, title } = props.subgallery;
return(
<>
<a href={url} data-attribute="SRL">
<img src={thumbnail} alt={title} />
</a>
</>
)
I haven't used the package so this is a bit of speculation. Hope it leads you in the right direction though.
EDIT
I think I misunderstood this library a bit. You do need both of those components. It looks like if you want to display full size images, you would do it the way you have it currently. However, if you want to use the lightbox feature with the nav at the bottom you would need to do something like:
<SimpleReactLightbox>
<SRLWrapper>
<div id="content-page-one" className="container content">
<div className="row">
{
gallery.resources.map((SUBGALLERY) =>{
return(
<Gallery key = {SUBGALLERY.id} subgallery={SUBGALLERY} />
)
})
}
</div>
</div>
</SRLWrapper>
</SimpleReactLightbox>
And then you would use div instead of an anchor tag:
<div className="col-md-6 col-12 col-image-half">
<img src={thumbnail} alt={title} />
</div>
This is pulled from the Code Sandbox examples they have. I would take a closer look there and see if they have the exact setup you're looking for. Notice also that they are using the Bootstrap styling framework as well, so in order for those styles to work you would need to install bootstrap to your dependencies.

Categories

Resources