Dynamically load images in create-react-app [duplicate] - javascript

I'm trying to display images in a shopping cart i'm making but its not showing up. Do i have to import each image? I know my paths are fine because it worked before.I think there might be something wrong in my product.js file but I can't figure it out.
Here is my Product.js
import React, { Component, PropTypes } from 'react';
class Product extends Component {
handleClick = () => {
const { id, addToCart, removeFromCart, isInCart } = this.props;
if (isInCart) {
removeFromCart(id);
} else {
addToCart(id);
}
}
render() {
const { name, price, currency, image, url, isInCart } = this.props;
return (
<div className="product thumbnail">
<img src={image} alt="product" />
<div className="caption">
<h3>
<a href={url}>{name}</a>
</h3>
<div className="product__price">{price} {currency}</div>
<div className="product__button-wrap">
<button
className={isInCart ? 'btn btn-danger' : 'btn btn-primary'}
onClick={this.handleClick}>
{isInCart ? 'Remove' : 'Add to cart'}
</button>
</div>
</div>
</div>
);
}
}
Product.propTypes = {
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
price: PropTypes.number,
currency: PropTypes.string,
image: PropTypes.string,
url: PropTypes.string,
isInCart: PropTypes.bool.isRequired,
addToCart: PropTypes.func.isRequired,
removeFromCart: PropTypes.func.isRequired,
}
export default Product;
The data comes from this product.js
const data = [
{
id: 1,
name: 'Reggae Blaster',
price: 10,
currency: 'GOLD',
image: '../assets/blaster_1.png'
},
{
id: 2,
name: 'Juicy Blaster',
price: 10,
currency: 'GOLD',
image: 'images/02.jpg'
},
{
id: 4,
name: 'Full Body Reggae Armor',
price: 20,
currency: 'GOLD',
image: 'images/04.jpg'
},
{
id: 6,
name: 'Reggae Spikes Left',
price: 5,
currency: 'GOLD',
image: 'images/06.jpg'
},
{
id: 5,
name: 'Reggae Spikes Right',
price: 5,
currency: 'GOLD',
image: 'images/05.jpg'
},
{
id: 3,
name: 'Black Full Body Reggae Armor',
price: 20,
currency: 'GOLD',
image: 'images/03.jpg'
}
];
export default data;
I am pulling all the data except the images just don't show up

Assuming that you are using webpack, you need to import the image in order to display it like
<img src={require('images/06.jpg')} alt="product" />
Now that your image data is dynamic,
directly specifying the import path like
<img src={require(image)} alt="product" />
doesn't work.
However you can import the image by making use of template literals like
<img src={require(`${image}`)} alt="product" />
So your code will look like
render() {
const { name, price, currency, image, url, isInCart } = this.props;
return (
<div className="product thumbnail">
<img src={require(`${image}`)} alt="product" />
<div className="caption">
<h3>
<a href={url}>{name}</a>
</h3>
<div className="product__price">{price} {currency}</div>
<div className="product__button-wrap">
<button
className={isInCart ? 'btn btn-danger' : 'btn btn-primary'}
onClick={this.handleClick}>
{isInCart ? 'Remove' : 'Add to cart'}
</button>
</div>
</div>
</div>
);
}
P.S. Also make sure that your image path is relative to the file you are importing them in.

img src={require(${filePath})}
-- working
you also need to add default to get exact URL
img src={require(`${filePath}.default`)}

I adding this comment so that future guys can benefit.
So the problem I faced was I had an array of people, and I needed to display the profile picture of each person
Solution
2 files :
data.js which contains an exported JSON object
main.js which has my react component
Step#1 : data.js
in data.js import all your local image asset files that you need.
ex.
import ProfilePicN from "./ProfilePicN.jpg";
export default [
{
"name": "PersonN",
"image": ProfilePicN
}
]
*important: no quotes around the import, quotes on everything else as they are all literals
Step#2:
import data from "./data.
.
.
.
/*inside the react component*/
{
data.map((dataItem,key)=> {
<img src={dataItem.image}>
})
}

You have to put those images in folder where your bundled application lives.

Related

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: mapping through a list of svg images

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>
))}
)}

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>

Add img into react state for display in custom dropdown

Goal
I need to develop a single-select dropdown menu that allows the user to choose from different images instead of words.
Background
I've downloaded react dropdown and imported into the file. The dropdown is working if I use words but I haven't been successful in making it display images instead.
What I've tried
First, in this.state, I tried adding a relative path to the image file. This simply rendered that path (duh). Next, I tried adding the img tag with the src pointing to the location of the image I want to display. The result is an image that seems to indicate that an image is supposed to be there.
Here is the code
import React from 'react';
import './EventContainer.css';
import { Dropdown } from 'reactjs-dropdown-component';
import { dining } from './EventContainerIcons.js';
class EventContainer extends React.Component {
constructor(props){
super(props);
this.state = {
...props.event,
activityIcon: [
{
id: 0,
title: <img src={dining} width="64" height="64" alt="dining icon" />,
selected: false,
key: 'activityIcon'
},
{
id: 1,
title: 'Orange',
selected: false,
key: 'activityIcon'
},
{
id: 2,
title: 'Strawberry',
selected: false,
key: 'activityIcon'
}
],
};
}
handleTypeChange = (e) => {
this.setState({
type: e.target.value
})
}
handleTimeChange = (e) => {
this.setState({
time: e.target.value
})
}
handleSummaryChange = (e) => {
this.setState({
summary: e.target.value
})
}
handleNotesChange = (e) => {
this.setState({
notes: e.target.value
})
}
resetThenSet = (id, key) => {
let temp = JSON.parse(JSON.stringify(this.state[key]));
temp.forEach(item => item.selected = false);
temp[id].selected = true;
this.setState({
[key]: temp
});
}
render(){
return (
<div className="eventContainer-flex">
<Dropdown
title="Event Type"
list={this.state.activityIcon}
resetThenSet={this.resetThenSet}
/>
<div>
<input
type="time"
value={this.state.time}
onChange={this.handleTimeChange}/>
</div>
<div>
<textarea
className="textarea-font"
placeholder="Write summary here"
value={this.state.summary}
onChange={this.handleSummaryChange}
cols={60}
rows={3} />
</div>
<div>
<textarea
className="textarea-font"
placeholder="Write notes here"
value={this.state.notes}
onChange={this.handleNotesChange}
cols={30}
rows={3} />
</div>
</div>
)
}
}
export default EventContainer;
just add the image name into the import. like a
import image from './EventContainerIcons/dining.png';
after that,
title: <img src={image} alt="empty" />
FYI: while you use image add a alt attribute to img tag.
reference link: https://codesandbox.io/s/falling-https-bkmf0

Categories

Resources