I'm currently following a tutorial and I tried to render some images coming from an array as shown in the tutorial but none of the images show up in the browser.
This is the component showing how I went about that.
import React from 'react';
export default function MasonryPost ({post, tagsOnTop}) {
const style = {backgroundImage: `url("${require(`../../assests/images/${post.image}`)}")`}
return (
<a className="masonry-post overlay" style={style} href={post.link}>
<div className="image-text">
<div>
<h2 className="image-title">{post.title}</h2>
</div>
</div>
</a>
)
}
When I inspect it in the browser, instead of the url link, it shows "object module"
This is where the images ought to come from
import moment from 'moment'
export default [
{
title: 'Do you want to code?',
date: moment().format('MMMM DD, YYYY'),
categories: ['Beginning your journey'],
link: '#',
image: 'journey.jpg'
},
{
title: 'Using AWS S3 for Storing Blog Images',
date: moment().format('MMMM DD, YYYY'),
categories: ['Cloud'],
link: '#',
image: 'cloud.jpg'
},
{
title: 'Highest paying Programming Languages in 2020',
date: moment().format('MMMM DD, YYYY'),
categories: ['Tect Culture', 'Tech News'],
link: '#',
image: 'Tech.jpg'
},
{
title: 'Brain Hacks For getting enough rest',
date: moment().format('MMMM DD, YYYY'),
categories: ['Brain Health'],
link: '#',
image: 'Brain.jpg'
},
{
title: 'How to manage time while you Program',
date: moment().format('MMMM DD, YYYY'),
categories: ['Time Management'],
link: '#',
image: 'Time.jpg'
},
{
title: 'Brain Hacks For Learning to Program',
date: moment().format('MMMM DD, YYYY'),
categories: ['Brain Health'],
link: '#',
image: 'Brain.jpg'
},
]
I saw a few things online about the issue coming from webpack.config.js, I tried most of their solutions but the problem still persists.
I have no idea what to do again. I would appreciate anyone's help.
You need to provide path to the file. What you are doing is providing the data of the file itself. You can also convert them to base64 form. But i guess, only removing the require call will be sufficient.
You don't need to require each image. You can simply use:
const style = {backgroundImage: `url("/assests/images/${post.image}")`}
Try this approach,
function MasonryPost({ post }) {
const style = {
background: `url("../assets/images/${post.image}") no-repeat`,
height: "200px",
width: "230px"
};
return (
<div className="masonry-post overlay" style={style} href={post.link}>
<div className="image-text">
<div>
<h2 className="image-title">{post.title}</h2>
</div>
</div>
</div>
);
}
Working code:- https://codesandbox.io/s/competent-bash-o34kd?file=/src/App.js:1452-1851
you can use this code instead of your code:
import React from 'react';
render(){
return (
<div style ={{backgroundImage: url("YourPath")}}>
<a href={post.link}>
<div className="image-text">
<div>
<h2 className="image-title">{post.title}</h2>
</div>
</div>
</a>
</div>
)
}
Related
While creating cards and using props in React.js I need to add an anchor tag(website:) and an image (image:) within a few elements in an array but am unable to figure out how. Of course, as seen below simply just adding an anchor tag etc does not work. Any help would be appreciated.
const projects = [
{
id: 1,
image: <img src="https://picture.jpg" alt="Coaching Website">
name: "Personal Coaching Website",
meaning:"A comprehensive website for a personal health and wellness coach"
website:
},
Rather than defining elements in an array, use the values, and map into the properties of the element.
const projects = [
{
id: 1,
image: "https://picture.jpg",
name: "Personal Coaching Website",
meaning: "A comprehensive website for a personal health and wellness coach",
website: "https://www.samplewebsite.com"
}
];
export default function App() {
return (
<div>
{projects.map(project => {
return (
<div>
<img src={project.image} />
<a href={project.website} />
</div>
);
})}
</div>
);
}
I'm trying to map through an array of objects, rendering local images, but have painfully found out that this can't be done the same way as rendering external urls, with the images not firing.
Not been able to find a solution without cheating and declaring local images declaratively - import Logo from ... - or placing the images in the public folder, which could give me cache issues down the line. I've tried image: require("") in the array but it doesn't seem to respond.
Surely this can be done dynamically? If anyone knows of a solution to the below it would really help me out.
Directory.jsx
this.state = {
categories: [
{
title: "Burgers",
image: "../../images/Burger_landing.jpeg",
id: 1
},
{
title: "Sides",
image: "../../images/Fries_main.jpeg",
id: 2
},
{
title: "Shakes",
image: "../../images/Shakes_main.jpeg",
id: 3
}
]
};
}
render() {
return (
<div className='menu__container-position'>
{this.state.categories.map(({ title, image, id }) => (
<DirectoryItem key={id} title={title} image={image} />
))}
</div>
);
}
DirectoryItem.jsx
const DirectoryItem = ({ title, image }) => {
return (
<div
className='menu__container-img'
style={{ backgroundImage: `${image}` }}
>
<h1>{title}</h1>
</div>
);
};
You should set the image URL like below
backgroundImage: `url(${image})`
Or
backgroundImage: "url("+image+")"
If images are not in a public path
backgroundImage: `url(${require(image)})`
This question involves next-seo library.
I am using a default config per the docs and attempting to override og:image, og:title, og:url, title for each product on an e-commerce site. When I inspect the <head/> element in devtools the correct tag injections are taking place. However, when using the Twitter and Facebook sharing debuggers these dynamic changes are not being scraped. I assumed functionality like this is core to this library and I wonder if I am overlooking something.
I implement my defaults in _app.js and inserting my per product overrides as high up my render tree as possible.
Default
export default {
titleTemplate: `Anne's Handmade | %s`,
title: 'Home',
description: 'One of a kind, handmade jewelry # affordable prices. 💎',
canonical: 'https://anneshandmade.herokuapp.com/',
facebook: {
appId: '2300738536877547'
},
openGraph: {
type: 'website',
url: 'https://anneshandmade.herokuapp.com/',
title: "Anne's Handmade | Home",
description: 'One of a kind, handmade jewelry # affordable prices. 💎',
site_name: "Anne's Handmade",
images: [
{
url: 'https://s3-us-west-1.amazonaws.com/shopping-site/assets/open-graph-2.jpeg',
width: '800',
height: '800',
alt: "Anne's Handmade Logo"
}
]
},
twitter: {
handle: '#BenjaminBrooke3',
site: '#BenjaminBrooke3',
cardType: 'summary_large_image'
}
}
_app.js
<Container>
<NextSeo config={SEO} />
<ApolloProvider client={apollo}>
<Page {...pageProps}>
<Component {...pageProps} />
</Page>
</ApolloProvider>
</Container>
Overrider per product
const { product, thumbIndex } = data
return (
<>
<NextSeo
config={{
title: product.title,
openGraph: {
title: `Anne's Handmade | ${product.title}`,
url: `https://anneshandmade.herokuapp.com/product?id=${product.id}`,
images: [
{
url: product.images[0],
width: 800,
height: 800,
alt: product.title
}
]
}
}}
/>
<ProductStyles>
<Thumbnails images={product.images} thumbIndex={thumbIndex} />
<LargeImage image={product.images[thumbIndex]} />
<ProductDetail product={product} user={user} />
</ProductStyles>
</>
)
Head
Is there something special that needs to be done when using a query param?
Facebook Sharing Debugger
Facebook shows both urls in redirects, but when I look at what the scraper actually returns, it is still the original default image, url, etc.
I am learning react and I am attempting to reuse code (I'm told that's one of the great things about react). I currently have the following markup with the data sets imported like so. I have attempted to loop through the data set using .map but its proving to be difficult. Is there a best practice (slightly discussion focued rather than just answerable as stack overflow outlines, but I'm attempting to learn) when it comes to looping through data. Thanks
JS
import {recommendedActivities3} from '../../data/mocks'
import {recommendedActivities4} from '../../data/mocks'
<Link className={`PageCell recommended`} to={`/places/top-activities/${recommendedActivities3.id}`}>
<div className={`restaurantCard-main recommended`}>
<span className="host-recommendation-text">Host recommended</span>
<div className={`restaurantCard recommended`}>
<img className={`photo activity`} src={recommendedActivities3.image_url} size="small" alt="activities" />
<div className={`restaurantCard-right`}>
<div className="name">{recommendedActivities3.name}</div>
<div className="description"><p>{recommendedActivities3.description}</p></div>
</div>
</div>
</div>
</Link>
<Link className={`PageCell recommended`} to={`/places/top-activities/${recommendedActivities4.id}`}>
<div className={`restaurantCard-main recommended`}>
<span className="host-recommendation-text">Host recommended</span>
<div className={`restaurantCard recommended`}>
<img className={`photo activity`} src={recommendedActivities4.image_url} size="small" alt="activities" />
<div className={`restaurantCard-right`}>
<div className="name">{recommendedActivities4.name}</div>
<div className="description"><p>{recommendedActivities4.description}</p></div>
{/*<CellContent recommendedActivities={recommendedActivities} recHeight={recHeight} normalHeight={normalHeight} />*/}
</div>
</div>
</div>
</Link>
Data
Below I have provided the structure of my data for reference. Not sure if it is necessary.
export const recommendedActivities4 = {
description: 'One of the best spots in SFs Famous: North Beach. Grab a coffee and just people watch for hours!',
id: 'tartine-bakery-and-cafe-san-francisco',
name: 'Tartine Bakery & Cafe',
image_url: 'https://s3-media3.fl.yelpcdn.com/bphoto/vTLu8G86IqIazm7BRqIH4g/o.jpg',
is_closed: false,
url:
'https://www.yelp.com/biz/nopa-san-francisco?adjust_creative=oj0judbJDVIHIVps_GJrXQ&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=oj0judbJDVIHIVps_GJrXQ',
review_count: 4636,
categories: [
{
alias: 'newamerican',
title: 'American (New)',
},
{
alias: 'modern_european',
title: 'Modern European',
},
],
rating: 4,
coordinates: {
latitude: 37.774905,
longitude: -122.437506,
},
transactions: ['restaurant_reservation'],
price: '$$$',
location: {
address1: '560 Divisadero St',
address2: null,
address3: '',
city: 'San Francisco',
zip_code: '94117',
country: 'US',
state: 'CA',
display_address: ['560 Divisadero St', 'San Francisco, CA 94117'],
},
phone: '+14158648643',
display_phone: '(415) 864-8643',
distance: 255.549722789804,
}
So lets say you have some small component that you want to use to just render one recommended activity link. it would look something like this
const RecommendedActivity = ({activity}) => {
return (
<Link className="PageCell recommended" to={`/places/top-activities/${activity.id}`}>
<div className="restaurantCard-main recommended">
<span className="host-recommendation-text">Host recommended</span>
<div className="restaurantCard recommended">
<img className="photo activity" src={activity.image_url} size="small" alt="activities" />
<div className="restaurantCard-right">
<div className="name">{activity.name}</div>
<div className="description"><p>{activity.description}</p></div>
</div>
</div>
</div>
</Link>
)
}
this makes it a reusable component. So then the way you would use it is like so:
first lets make an array of recommended activities to work with const seed = [recommendedActivities3, recommendedActivities4]
now in the render method you would just call the particular component for each element in the array
{ seed.map( (activity, idx) => <RecommendedActivity activity={activity} key={idx}/>)}
I want to display images in the sports array using map(). but not working
<div className="row">
{this.state.sports.map(function(sport, index){
return (
<div className="col-md-3" key={index}>
<h3 className="text-center">{this.state.sports.name}</h3>
<img src={ require('./../assets/images/'+ {this.state.sports.name} +'.jpg') } width="300px" height="180px" />
<button className="btn btn-info btn-sm" type="submit" onClick={this.join_in_sport} >JOIN</button>
</div>
)
}.bind(this))}
</div>
The problem seems to lie in how you are building the pathname for your image. Same for your <h3> tag.
src={ require('./../assets/images/'+ {this.state.sports.name} +'.jpg') }
If this.state.sports is an array, and not an object, then it can't possibly have a name key. I think you meant to print the current objects name for each iteration in your map().
So try:
<h3 className="text-center">{this.state.sports.name}</h3>
<img src={ require('./../assets/images/'+ {sport.name} +'.jpg') } width="300px" height="180px" />
This is assuming your array looks something like:
[
{name: "foo"},
{name: "bar"}
]
I have encountered the same problem,
the image folder in src doesn't work.
I moved the image folder to public and it works fine.
function App() {
const moviesData = [
name: "Terminator: Dark Fate",
img: "./badboy3.jpg", //image in public folder
},
];
const movieList = moviesData.map((movie, i) => {
return <Movie key={i} movieName={movie.name} movieImg={movie.img} />;
});
return (
<div>
{movieList}
</div>
);
}
export default App;
I was following the React beginners tutorial tried to call images dynamically by importing them as variables but this simply didn't work when trying to call them in another file (App.js) using the .map() function. Code below:
import katieImg from "../images/Katie.png";
import starImg from "../images/Katie.png";
export default [
{
img: { katieImg },
star: { starImg },
rating: "5.0",
reviewCount: 6,
location: "USA",
title: "Life Lessons with Katie Zaferes",
price: 136,
},
];
So instead I had to get rid of the dynamically imported variables and put the images folder in the public folder. This worked. Code below:
export default [
{
img: "../images/Katie.png",
star: "../images/Star.png",
rating: "5.0",
reviewCount: 6,
location: "USA",
title: "Life Lessons with Katie Zaferes",
price: 136,
},
];