React: mapping through a list of svg images - javascript

I am trying to map through a list of svg images and show enough description corresponding to the svg image.
index.js
import {ReactComponent as Pic1} from "../../../../assets/buyer-1.svg";
import {ReactComponent as Pic2} from "../../../../assets/buyer-2.svg";
import {ReactComponent as Pic3} from "../../../../assets/buyer-3.svg";
const data = [
{
id: `1`,
title: "Coming soon",
description:'',
img: Pic1,
},
{
id: `2`,
title: "Coming soon",
description:'',
img: Pic2,
},
{
id: `3`,
tile: "Coming soon",
description:'',
img: Pic3,
},
]
function Test() {
return (
{data.map(({ id, title,description, img }) => (
<div key={id} className="guest--item swiper-slide">
<div>
<img key={id} src={img} alt='mySvgImage' />
<h1>{title}</h1>
<h2>{description}</h2>
</div>
</div>
))}
)}
currently when i check my react website i can only see mySvgImage which is the alt 3 times and cant see the actual image

You are importing SVG's as React Component hence you should use them as Component itself.
In you code you are passing a React Component (SVG's which you imported as React Component) as a src attribute to an <img> tag which is invalid.
import React from "react";
import ReactDOM from "react-dom";
import {ReactComponent as Pic1} from "../../../../assets/buyer-1.svg";
import {ReactComponent as Pic2} from "../../../../assets/buyer-2.svg";
import {ReactComponent as Pic3} from "../../../../assets/buyer-3.svg";
const data = [
{
id: `1`,
title: "Coming soon",
description: "",
Image: Pic1
},
{
id: `2`,
title: "Coming soon",
description: "",
Image: Pic2
},
{
id: `3`,
tile: "Coming soon",
description: "",
Image: Pic3
}
];
function Test() {
return (
<>
{data.map(({ id, title, description, Image }) => (
<div key={id}>
<div>
<Image /> {/* Use Image as Component */}
<h1>{title}</h1>
<h2>{description}</h2>
</div>
</div>
))}
</>
);
}

Because you are importing your images the wrong way. I have made this working CodeSandbox which is exactly the same as your example. Check how I imported images and it's working just fine. CodeSandbox

Where you got it wrong is importing SVG as React Component and using for a src attribute in an img tag.
So u don't need to import as ReactComponent.
You can import this way.
import Pic1 from "../../../../assets/buyer-1.svg";
import Pic1 from "../../../../assets/buyer-1.svg";
import Pic2 from "../../../../assets/buyer-2.svg";
import Pic3 from "../../../../assets/buyer-3.svg";
const data = [
{
id: `1`,
title: "Coming soon",
description:'',
img: Pic1,
},
{
id: `2`,
title: "Coming soon",
description:'',
img: Pic2,
},
{
id: `3`,
tile: "Coming soon",
description:'',
img: Pic3,
},
]
function Test() {
return (
{data.map(({ id, title,description, img }) => (
<div key={id} className="guest--item swiper-slide">
<div>
<img key={id} src={img} alt='mySvgImage' />
<h1>{title}</h1>
<h2>{description}</h2>
</div>
</div>
))}
)}

Related

Mapping over an array to render images

I am trying to create cards that display an image with a description. I have an array with the data for each card. The cards are appearing with the description, but the images aren't rendering.
The Card Component:
export const Card = (props) => (
<div className="card">
<a href={props.href} target="_blank">
<img className="card-image" src={props.src} alt={props.alt} />
<h3 className="card-title">{props.title}</h3>
<p className="card-description">{props.description}</p>
</a>
</div>
);
A Callback Function and the Projects component that maps through the array:
const renderCard = (project) => (
<Card
href={project.href}
src={project.src}
alt={project.alt}
title={project.title}
description={project.description}
key={project.id}
/>
);
const Projects = () => {
const cardElements = projects.map(renderCard);
return (
<div id="projects-section">
<h1 className="title">Projects</h1>
{cardElements}
</div>
);
};
And the data is coming from this projects array:
import retreat from "../images/retreat.jpg";
import guess from "../images/guessTheWord.jpg";
import jsKeyboard from "../images/drum-kit.jpg";
import ptWebsite from "../images/ptWebsite.jpg";
import stickyNotes from "../images/sticky-notes-app.jpg";
import firstWebsite from "../images/my-first-website.jpg";
export const projects = [
{
href: "https://patgramo.github.io/unplugged-retreat/",
src: { retreat },
alt: "Card image",
title: "Company Retreat Website",
description:
"I created a website for a company retreat to practice using media queries with CSS. This was a project through Skillcrush.",
id: "01"
},
{
href: "https://patgramo.github.io/guess-the-word/",
src: { guess },
alt: "Card image",
title: "Guess The Word Game",
description:
"Here I created a guess-the-word game using my JavaScript and CSS knowledge. This was the final project in Skillcrush's JavaScript course.",
id: "02"
}
];
The values you're setting for src are objects, not strings. On your first entry src is an object with a retreat property. Remove the curlies.
{
href: "https://patgramo.github.io/unplugged-retreat/",
src: retreat,
alt: "Card image",
title: "Company Retreat Website",
description:
"I created a website for a company retreat to practice using media queries with CSS. This was a project through Skillcrush.",
id: "01"
},

React JS: How to add multiple placeholder object inside components

Sorry this question might be duplicated, but none of the existing answers helped me
I'm a beginner in React and js
I want to add multiple objects inside the component
Like:
src={url}
name={text}
subTitle={subtext}
my index.js
const tableColumns = [
{
title: 'Title/Artist',
dataIndex: 'name',
key: 'name',
render: (text) => (
<div className="d-flex align-items-center">
<AvatarStatus
shape="square"
src="https://i.scdn.co/image/ab67616d00001e02bd26ede1ae69327010d49946"
name={text}
subTitle="Dua Lipa"
/>
</div>
),
},
];
return (
<>
<Table
className="no-border-last"
columns={tableColumns}
dataSource={recentReleasesData}
rowKey='id'
pagination={false}
/>
</>
my data.js
export const RecentReleasesData = [
{
id: '#5332',
artwork: 'https://i.scdn.co/image/ab67616d00001e02bd26ede1ae69327010d49946',
name: 'Future Nostalgia',
artist: 'Dua Lipa',
label: 'Warner Records',
barcode: '19029500',
releasedate: '2021-02-11',
tracks: '11',
promolink: 'Smart Link',
status: 'Approved',
},
{
id: '#6438',
artwork: 'https://i.scdn.co/image/ab67616d00001e02caf82abb2338880577e472be',
name: 'Love',
artist: 'Someonw',
label: 'UMG Records',
barcode: '50029500',
releasedate: '2017-08-21',
tracks: '2',
promolink: 'Smart Link',
status: 'Rejected',
},
];
My comp AvatarStatus.js
import React from 'react';
import PropTypes from 'prop-types'
import { Avatar } from 'antd';
const renderAvatar = props => {
return <Avatar {...props} className={`ant-avatar-${props.type}`}>{props.text}
</Avatar>;
}
export const AvatarStatus = props => {
const { name, suffix, subTitle, id, type, src, icon, size, shape, gap, text,
onNameClick } = props
return (
<div className="avatar-status d-flex align-items-center">
{renderAvatar({icon, src, type, size, shape, gap, text })}
<div className="ml-2">
<div>
{
onNameClick ?
<div
onClick={() => onNameClick({name, subTitle, src, id})}
className="avatar-status-name clickable">{name}
</div>
:
<div className="avatar-status-name"><a href="javascript:void(0)">
{name}</a>
</div>
}
<span>{suffix}</span>
</div>
<div className="text-muted avatar-status-subtitle">{subTitle}</div>
</div>
</div>
)
}
AvatarStatus.propTypes = {
name: PropTypes.string,
src: PropTypes.string,
type: PropTypes.string,
onNameClick: PropTypes.func
}
export default AvatarStatus;
https://reactjs.org/docs/components-and-props.html
components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions.
codepen example
I found the solution
index.js
render: (_, record) => (
<Flex>
<AvatarStatus
shape="square"
size={50}
src={record.artwork}
name={record.title}
subTitle={record.artist}/>
</Flex>
),

React MUI, How to append to a Masonry Image List

I'm trying to use the React MUI Masonry Image List component with the infintie scroll component. They seem to work pretty great together.
However, the issue I'm having is appending to the Masonry image list. I successfully append new images, but the whole masonry moves jump and becomes jittery when new images are loaded.
I wonder if it's possible just to add the images to the bottom of the page without the whole thing spazzing out.
Here is a code the illustrates this, basically I just modified the Masonry image list demo:
import * as React from 'react';
import Box from '#mui/material/Box';
import ImageList from '#mui/material/ImageList';
import ImageListItem from '#mui/material/ImageListItem';
import InfiniteScroll from "react-infinite-scroll-component";
import { useEffect, useState } from "react";
export default function MasonryImageList() {
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
const [items, setItems] = useState([]);
const fetchMore = async (itemData) =>{
await sleep(2000)
setItems(prev_items => [...prev_items,...itemData])
}
useEffect(() => {
fetchMore(itemData);
}, []);
return (
<Box id="scrolableDiv" sx={{ width: 800, height: 800, overflowY: 'scroll' }}>
<ImageList variant="masonry" cols={3} gap={8}>
<InfiniteScroll
dataLength={items.length}
next={fetchMore(itemData)}
hasMore={true}
loader={<h4>Loading...</h4>}
scrollableTarget= "scrolableDiv"
>
{items.map((item) => (
<ImageListItem key={item.img}>
<img
src={`${item.img}?w=248&fit=crop&auto=format`}
srcSet={`${item.img}?w=248&fit=crop&auto=format&dpr=2 2x`}
alt={item.title}
loading="lazy"
/>
</ImageListItem>
))}
</InfiniteScroll>
</ImageList>
</Box>
);
}
const itemData = [
{
img: 'https://images.unsplash.com/photo-1549388604-817d15aa0110',
title: 'Bed',
},
{
img: 'https://images.unsplash.com/photo-1525097487452-6278ff080c31',
title: 'Books',
},
{
img: 'https://images.unsplash.com/photo-1523413651479-597eb2da0ad6',
title: 'Sink',
},
{
img: 'https://images.unsplash.com/photo-1563298723-dcfebaa392e3',
title: 'Kitchen',
},
{
img: 'https://images.unsplash.com/photo-1588436706487-9d55d73a39e3',
title: 'Blinds',
},
{
img: 'https://images.unsplash.com/photo-1574180045827-681f8a1a9622',
title: 'Chairs',
},
{
img: 'https://images.unsplash.com/photo-1530731141654-5993c3016c77',
title: 'Laptop',
},
{
img: 'https://images.unsplash.com/photo-1481277542470-605612bd2d61',
title: 'Doors',
},
{
img: 'https://images.unsplash.com/photo-1517487881594-2787fef5ebf7',
title: 'Coffee',
},
{
img: 'https://images.unsplash.com/photo-1516455207990-7a41ce80f7ee',
title: 'Storage',
},
{
img: 'https://images.unsplash.com/photo-1597262975002-c5c3b14bbd62',
title: 'Candle',
},
{
img: 'https://images.unsplash.com/photo-1519710164239-da123dc03ef4',
title: 'Coffee table',
},
];
If you see any glaring errors, please point them out, I've just started with React.
I've faced this similar problem. What worked for me was to supply <img> with a minimum height value.
ie.
<img
src={`${item.img}?w=248&fit=crop&auto=format`}
srcSet={`${item.img}?w=248&fit=crop&auto=format&dpr=2 2x`}
alt={item.title}
loading="lazy"
style={{ minHeight: 10 }} //Added minHeight; 10 is just a sample value
/>
Since masonry lists depend on the height of the element, minHeight serves as a placeholder value while the img has not yet loaded.

React - dynamic background image

Im new to React.
Im building and app where one of my components need to have a dynamic background image.
i have the menu-item component where it gets 2 props one of them is imgName which hold the the name like shoes.jpg.
for some reason i cant get it to be the background image.
here some of the code i have wrote
main-menu component
import React from 'react';
import MenuItem from '../menu-item/menu-item.component'
import './main-menu.style.scss'
class MainMenu extends React.Component {
constructor() {
super()
this.state = {
sections: [{
title: 'pants',
imgName: 'pants.jpg',
id: 1
},
{
title: 'shirts',
imgName: 'shirts.jpg',
id: 2
},
{
title: 'hats',
imgName: 'hats.jpg',
id: 14
},
{
title: 'jackets',
imgName: 'jackets.jpg',
id: 12
},
{
title: 'shoes',
imgName: 'shoes.jpg',
id: 6
}
]
}
}
render() {
return (
<div className="main-menu">
{this.state.sections.map(({ title, id, imgName }) => {
return (
<MenuItem imgName={imgName} title={title} key={id} />
)
})}
</div>
)
}
}
export default MainMenu
menu-item component
import React from 'react';
import './menu-item.styles.scss'
const MenuItem = ({ title,imgName }) => (
<div style={{backgroundImage:`url(../../../public/assets//'${imgName}')`}} className="menu-item">
<div className="content">
<h1 className="title">{title}</h1>
<span>buy now</span>
</div>
</div>
)
export default MenuItem;
You can try it:
<div style={{backgroundImage:`url(require(../../../public/assets//'${imgName}'))`}} className="menu-item">
<div className="content">
<h1 className="title">{title}</h1>
<span>buy now</span>
</div>
</div>

How to display array of text in react?

I'm making a portfolio website in ReactJS. I'm trying to display an array of text under desc in HomePageContent.js. I'm not sure how display each of the paragraphs. I think I have to map the paragraphs, but I'm not sure how to do that.
Relevent Code
HomePageContent.js
// Image import statements
import Im1 from '../img/Im1.png';
import Im2 from '../img/Im2.jpg';
import Im3 from '../img/Im3.jpg';
let HomePageContent = {
job: [{
logo: Im1,
alt: 'Logo1',
companyName: 'comp1' ,
link: 'link1',
title: 't1',
duration: 'dur1',
location: 'loc1',
desc: {
text: 'p1',
text: 'p2',
text: 'p3',
text: 'p4'
},
id: 1
}
export default HomePageContent;
Job.js
import React from 'react';
import '../css/Experience.css';
function Job(props) {
console.log(props.name);
const jobList = props.job.map(j =>
<div className='exp-container'>
<img src={j.logo} alt={j.alt} />
<div className='description'>
<div>
<a href={j.link} rel='noopener noreferrer' target='_blank'>
{j.companyName}
</a>
</div>
<div>{j.title}</div>
<div>{j.duration}</div>
<div>{j.location}</div>
<div><p>{j.desc}</p></div>
</div>
</div>
)
return (
<div>{jobList}</div>
);
}
export default Job;
You're right, mapping over the paragraphs would work, but I recommend changing the value inside desc to an array so that you have an easier time doing that.
...
desc: [
'p1',
'p2',
'p3',
'p4',
],
...
Then, in your JSX, you can map over it and put each of them in their own set of <p> tags.
<div>
{j.desc.map(paragraph => <p>{paragraph}</p>)}
</div>
This works because the map function returns an array of whatever you return in the provided fat arrow function, and JSX will automatically render an array of JSX elements one right after the other. So it looks like this in the rendered HTML:
<div>
<p>p1</p>
<p>p2</p>
<p>p3</p>
<p>p4</p>
</div>

Categories

Resources