Import images from object array in map with Webpack - javascript

I have an array of objects that looks like this:
export const NGOarray = [
{
name: "1% for the Planet ",
description:
"A leading global nonprofit, building a movement of businesses and individuals delivering philanthropic support to environmental organizations working on the front lines for our planet.",
link: "https://onepercentfortheplanet.org/",
category: ["water", "everything"],
logo: "1fortheplanet.webp",
},
{
name: "4ocean",
description:
"As both a public benefit corporation and Certified B Corp, we’re committed to ending the ocean plastic crisis.",
link: "https://www.4ocean.com",
category: ["water", "everything"],
logo: "4 Ocean.svg",
} ]
The logo property maps to the filename they have in a folder.
I'm trying to map through that array and show each image like this:
{NGOarray.map((org) => {
<div key={org.name}>
{org.logo && (
<img
src={
require(`../assets/organizations/${org.logo}`)
.default
}
/>
)}
<h3 className="text-2xl font-sans mb-4">{org.name}</h3>
<p>{org.description}</p>
</div>
);
}
But the image won't show up.
Any idea how I can get it to work?

Okay, this seems to have worked, leaving answer here for reference:
function importAll(r) {
return r.keys().map(r);
}
const logos = importAll(
require.context("../assets/organizations/", false, /\.(png|jpe?g|svg)$/)
);
And when mapping the array:
{NGOarray.map((org, index) => {
<div key={org.name}>
{org.logo && <img src={logos[index]} alt={org.name} />}
<h3 className="text-2xl font-sans mb-4">{org.name}</h3>
<p>{org.description}</p>
</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"
},

ReactJs : How to display a specific data of an object from an array of objects with a click

I have an Array with a list of objects , each object contains an ID ,title , job description and salary. I saved it in a separate file as below :
export const CareerList = [
{
id: 1,
title: "Junior Accountant",
salary: "1500$",
jobDescription: [
"Maintains financial records for subsidiary companies by analyzing balance sheets and general ledger accounts",
"Reconciles general and subsidiary bank accounts by gathering and balancing information",
"Provides financial status information by preparing special reports; completing special projects",
"Corrects errors by posting adjusting journal entries",
"Maintains general ledger accounts by reconciling accounts receivable detail and control accounts; adjusting entries for amortizations prepaids; analyzing and reconciling retainage and accounts payable ledgers; preparing fixed asset depreciation and accruals",
"Secures financial information by completing database backups; keeping information confidential",
"Maintains accounting controls by following policies and procedures; complying with federal, state, and local financial legal requirements",
"Updates job knowledge by participating in educational opportunities; reading professional publications",
"Accomplishes accounting and organization mission by completing related results as needed",
],
},
{
id: 2,
title: "Research Analyst",
salary: "3500$",
jobDescription: [
"Support the Director of Research & Impact and the Research Manager in implementing all phases of ANDE research projects",
"Design and administer surveys and conduct secondary data collection from online sources to aggregate data related to global SGB support.",
"Clean and analyze data to identify key trends, and develop reports communicating these insights to practitioners",
"Track new research developments related to SGBs and collect and synthesize this research for ANDE members.",
"Provide support in identifying and selecting consultants and interns to support research activities and coordinate with these consultants and interns to carry out research.",
"Manage the content of ANDE’s various online research portals, such as www.galidata.org, http://ecosystems.andeglobal.org, and www.andeglobal.org/knowledge-hub.",
"Manage administrative functions related to project funding (e.g. tracking expenses).",
],
},
I am trying to create two modals , one modal which only display the job titles with the button job details next to it , and if I clicked on a particular job button, the list modal should hide and another modal with that specific job details should show, any suggestion how it can be done?
import { CareerList } from "../data/Careers";
import ButtonMedium from "../UI/ButtonMedium";
import JobDetails from "./JobDetails";
const Backdrop = (props) => {
return <div className={classes.backdrop} onClick={props.onHide}></div>;
};
const CareerOverlay = () => {
const [showJobDetails, setShowJobDetails] = useState(false);
const displayJobDetails = () => {
setShowJobDetails(true);
};
return (
<>
<div className={classes.careerBox}>
{CareerList.map((job, index) => {
return (
<div className={classes.jobItem} key={index}>
<h2>{job.title}</h2>
<ButtonMedium onClick={displayJobDetails}>
Job Detail
</ButtonMedium>
{showJobDetails && (
<JobDetails careerList={CareerList} id={job.id} />
)}
</div>
);
})}
</div>
</>
);
};
const CareerOpportunities = (props) => {
return (
<>
{reactDom.createPortal(
<Backdrop onHide={props.onHide} />,
document.getElementById("backdrop")
)}
{reactDom.createPortal(
<CareerOverlay onShow={props.onShow} />,
document.getElementById("career")
)}
</>
);
};
export default CareerOpportunities;
import React from "react";
import classes from "./JobDetails.module.css";
const JobDetails = (props) => {
const particularJob = props.careerList.find((job) => job.is === props.id);
return (
<div className={classes.jobBox}>
<h1>{particularJob.title}</h1>
</div>
);
};
export default JobDetails;
Although the other answer seems alright, I'd also advise you to use portals for modals in React, and by that way you won't be bothered by stacking order when you're styling both modals.
Read more about portals here:
https://reactjs.org/docs/portals.html
You can split each item using new child component. So each item can manage modal state individually.
const CareerListItem = (props) => {
const [showJobDetails, setShowJobDetails] = useState(false);
const displayJobDetails = () => {
setShowJobDetails(true);
};
return (
<div className={classes.jobItem} key={index}>
<h2>{job.title}</h2>
<ButtonMedium onClick={displayJobDetails}>
Job Detail
</ButtonMedium>
{showJobDetails && (
<JobDetails job={props.job} />
)}
</div>
)
}
const CareerOverlay = () => {
return (
<>
<div className={classes.careerBox}>
{CareerList.map((job, index) => {
return (
<CareerListItem job={job} />
)
})}
</div>
</>
);
};
...
const JobDetails = (props) => {
return (
<div className={classes.jobBox}>
<h1>{props.job.title}</h1>
<div>details here...</div>
</div>
);
};

Images Won't Load with Array in React

I've been trying to learn React over the past few weeks, and have decided to go through the LamaDev tutorial series. Yesterday I started with the portfolio tutorial (https://www.youtube.com/watch?v=hQjlM-8C4Ps&t=2798s) but have been stuck with trying to load images in my array.
I went ahead and built a component called 'Product' which the code can be found below. After that I followed the instructions and built the ProductList component which is suppose to show each of my products that are in my data.js file. I have gone and posted those below.
The problem I am running in to is that if I use a random img link from the internet the image gets imported into my product and show through my product list. However this is not what I am wanting to do since there are some images of my own I wanted to use.
When my Product.jsx tried to use a image I have saved in src/assets/img/ the img won't load. I tried using the require tag but it still is not working. I have also gone ahead and uploaded everything to my github page which can be found here and used as a reference.
I'm really not sure what I've done wrong here since everything looks right, but still know the issue is falling between the keyboard and the chair.
Thanks for any help
Product.jsx
import "./product.css";
const Product = ({ img, link }) => {
return (
<div className="p">
<div className="p-browser">
<div className="p-circle"></div>
<div className="p-circle"></div>
<div className="p-circle"></div>
</div>
<a href={link} target="_blank" rel="noreferrer">
<img src={img} alt="" className="p-img" />
</a>
</div>
);
};
export default Product;
ProductList.jsx
import Product from "../product/Product";
import "./productList.css";
import { products } from "../../data";
const ProductList = () => {
return (
<div className="pl">
<div className="pl-texts">
<h1 className="pl-title">Create & inspire. It's Jon</h1>
<p className="pl-desc">
Jon Snow is a creative portfolio that your work has been waiting for.
Beautiful homes, stunning portfolio styles & a whole lot more awaits
inside.
</p>
</div>
<div className="pl-list">
{products.map((item) => (
// console.log(item)
<Product key={item.id} img={item.img} link={item.link} />
))}
</div>
</div>
);
};
export default ProductList;
data.js
export const products = [
{
id: 1,
img: require("./assets/img/theBestTestSite.jpg"),
link: "http://google.com",
},
{
id: 2,
img: require("./assets/img/theBestTestSite.jpg"),
link: "http://google.com",
},
{
id: 3,
img: require("./assets/img/theBestTestSite.jpg"),
link: "http://google.com",
},
];
In data.js try to import images first instead of require
import img1 from "./assets/img/theBestTestSite.jpg"
export const products = [
{
id: 1,
img: img1,
link: "http://google.com",
},
// and same for others
];

Part of function Component wont render in React even though same code works for another component

I am working on a React website. I am using a function component to render a piece of code by mapping the array. This is the code
import React from 'react'
import './DedicatedServer.css'
function DedicatedServer() {
const features = [
{
id: 1,
title: "Performance",
text: "Random text long enough to take you anywhere. I am not sure what to write right now but it will come out to be good"
},
{
id: 2,
title: "Secure",
text: "Random text long enough to take you anywhere. I am not sure what to write right now but it will come out to be good"
},
{
id: 3,
title: "Speed",
text: "Random text long enough to take you anywhere. I am not sure what to write right now but it will come out to be good"
},
{
id: 4,
title: "Price",
text: "Random text long enough to take you anywhere. I am not sure what to write right now but it will come out to be good"
},
{
id: 5,
title: "Uptime",
text: "Random text long enough to take you anywhere. I am not sure what to write right now but it will come out to be good"
},
{
id: 6,
title: "Live Support",
text: "Random text long enough to take you anywhere. I am not sure what to write right now but it will come out to be good"
},
]
return (
<div className="dedicated-server-container">
<div>
<h2 className="dedicated-server-heading">100GBPS for your needs</h2>
<p className="dedicated-server-text">100GBPS provides you with unrivalled performance, support, and reliability</p>
<p className="dedicated-server-text">Everything you can think of when you want to buy a dedicated server</p>
<div className="dedicated-features">
{features.map((feature, i) => {
<div key={i} className="dedicated-feature">
<h3 className="feature-heading">{feature.title}</h3>
<p className="feature-text">{feature.text}</p>
</div>
})}
<h1>Hello there!</h1>
</div>
</div>
</div>
)
}
export default DedicatedServer
Everything else works as expected but the block inside the curly braces does not render. I checked the console and there are no errors either.
I checked out some answers on Stack overflow related to problem with rendering but I am following everything and I am not really sure what am I missing.
I am using the same method in another file and it works just fine. I know this is a pretty simple problem and I am missing something really silly here but can you point out what is the issue here?
This is the piece of code for the other file and it works just fine.
import React from 'react'
import cloudlinux from './vector-logo/cloudlinux.svg'
import litespeed from './vector-logo/litespeed.svg'
import letsencrypt from './vector-logo/lets-encrypt.svg'
import cloudflare from './vector-logo/cloudflare.svg'
import cpanel from './vector-logo/cpanel.svg'
import './Vendors.css'
function Vendors() {
const vendorList = [
{
id: 1,
title: "Cloudflare",
img: `${cloudflare}`
},
{
id: 2,
title: "LiteSpeed",
img: `${litespeed}`
},
{
id: 3,
title: "Let's Encrypt",
img: `${letsencrypt}`
},
{
id: 4,
title: "Cloud Linux",
img: `${cloudlinux}`
},
{
id: 5,
title: "cPanel",
img: `${cpanel}`
}
]
return (
<div className="vendor-div">
<h2 className="vendor-text">Our Vendors</h2>
<div key={vendorList.id} className="vendors">
{vendorList.map((vendors, index) => (
<img key={index} className="vendor-image" alt={vendors.title} src={vendors.img}/>
))}
</div>
</div>
)
}
export default Vendors
This is the answer I found on stack overflow and I am guessing that this is not the problem here.
Link to the problem
You have to return the created div from inside the map like this
{features.map((feature, i) => {
return <div key={i} className="dedicated-feature">
<h3 className="feature-heading">{feature.title}</h3>
<p className="feature-text">{feature.text}</p>
</div>
})}
Alternatively you can use parenthesis instead of {} in the map functions. Parenthesis will implicitly return the JSX inside of them
{features.map((feature, i) => (
<div key={i} className="dedicated-feature">
<h3 className="feature-heading">{feature.title}</h3>
<p className="feature-text">{feature.text}</p>
</div>
))}

Chat map with react js, objects inside array

I'm trying to make a basic chat.
I want that for every contact I could save the messages from the both users and show them on the screen (just like chat in whatsapp web).
My code:
const [chatArr , setChatArr] = useState([
{
id: "v7fAa5OltrU=",
from: "Shai Dayan",
newMsg:{
msgs: [
{sender: 0, text:"Hello there, I'm using Chat !"},
{sender: 1, text:"Hello there, I'm using Chat !"}
]
},
group: false,
players: ['Shai Dayan']
},
And I'm trying to map this texts like this:
{chatArr[fullChat].newMsg.msgs.map((element,index)=>{
return <div className='speech-bubble'>
<div className="text-msg">
<div className='name-msg'>
<span className='from'>{chatArr[fullChat].from}</span> <br/>
{element.text}
</div>
<div>
</div>
</div>
</div>
})}
but it is not working..How can I make a array of objects that each object will contain the sender and the text and map it by the order?
From the array you posted here is how you can map over it.
You need to have a nested map, first to map over your chats and then to map over each message in the chat
{
chatArr && chatArr.map((chat,index) => {
return (
<>
{
chat.newMsg.msgs.map((msg,idx) => {
return (
<div className='speech-bubble'>
<div className="text-msg">
<div className='name-msg'>
<span className='from'>{chat.from}</span>
<br/>
{msg.text}
</div>
</div>
</div>
)
})
}
</>
)
}
}

Categories

Resources