Images Won't Load with Array in React - javascript

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
];

Related

How to use images in the array in the react?

I am creating a website. I am a beginner. I have an issue. I have an array of react components. I don’t know can I use React components as the array elements. They are images, imported from the folder of my project. Also, I have an array of names of news companies. The idea is to create blocks with the name and image above. I want to create blocks according to the my images array length. So if the length of this array is 4, the cards I have 4. The issue is I can't display images, I imported them to my project. Main code is in the main page component. Also, I have a component called Author Card. In it, I have a React component, that receives name and image as the props and put them in the card Html block.
Here is my main page component code:
import React from 'react';
import AuthorCard from "./MainPageComponents/AuthorCard";
import BBC_Logo from '../assets/images/BBC_Logo.png';
import FOX_Logo from '../assets/images/FOX_Logo.png';
import CNN_Logo from '../assets/images/CNN_logo.png';
import ForbesLogo from '../assets/images/forbes-logo.png';
function MainPage(props) {
const channels = [
{
name: 'BBC',
index: 1
},
{
name: 'FOX',
index: 2
},
{
name: 'CNN',
index: 3
},
{
name: 'FORBES',
index: 4
},
];
const logos = [
<BBC_Logo key={1} />,
<FOX_Logo key={2}/>,
<CNN_Logo key={3}/>,
<ForbesLogo key={4}/>
];
return (
<div className="main-page">
<div className="main-page_container">
<section className="main-page_channels">
{channels.map( (channel) => {
logos.map( (logo) => {
return <AuthorCard name={channel.name} img={logo} />
})
})}
</section>
</div>
</div>
);
}
export default MainPage;
Here is my Author Card component code:
import React from 'react';
function AuthorCard(props) {
return (
<div className="author-card">
<div className="author-img">
{props.img}
</div>
<div className="author-name">
{props.name}
</div>
</div>
);
}
export default AuthorCard;
Please, help!
I would handle this a bit differently. First thing the way you import your logos is not imported as a component. Rather you get the path/src of the image which you can then use in a component. Read more about that here: https://create-react-app.dev/docs/adding-images-fonts-and-files/
So the way I would do this is to put the logo img src into your channels array and then pass that img src to the AuthorCard component. Then in the AuthorCard component your use a component to render the image. Like this:
import React from "react";
import BBC_Logo from "../assets/images/BBC_Logo.png";
import FOX_Logo from "../assets/images/FOX_Logo.png";
import CNN_Logo from "../assets/images/CNN_logo.png";
import ForbesLogo from "../assets/images/forbes-logo.png";
export default function App() {
return (
<div className="App">
<MainPage />
</div>
);
}
const channels = [
{
name: "BBC",
index: 1,
img: BBC_Logo
},
{
name: "FOX",
index: 2,
img: FOX_Logo
},
{
name: "CNN",
index: 3,
img: CNN_Logo
},
{
name: "FORBES",
index: 4,
img: ForbesLogo
}
];
function MainPage(props) {
return (
<div className="main-page">
<div className="main-page_container">
<section className="main-page_channels">
{channels.map((channel) => {
return <AuthorCard name={channel.name} img={channel.img} />;
})}
</section>
</div>
</div>
);
}
function AuthorCard(props) {
return (
<div className="author-card">
<div className="author-img">
<img src={props.img} alt="author card" />
</div>
<div className="author-name">{props.name}</div>
</div>
);
}
Here, we are using the map function to iterate over the channels array and render an AuthorCard component for each channel. We pass the name property to the AuthorCard component, as well as the corresponding logo from the logos array.
Note that we are also passing a key prop to the AuthorCard component to help React identify each component uniquely. In this case, we're using the index property of each channel object.

Image is not uploading in React. instead alt tag is showing

In my project i have make a main.jsx in which i provide image link and description in array of 3 item. then i take those to another component name Photo through Photowall.jsx . But image is showing of alt. not the imgaeLink
<figure className='figure'>
<img src={post.imageLink} alt={post.description}/>
</figure>
my main.jsx -
import Header from './Header'
import Photowall from './Photowall'
const posts = [
{
id:"0",
description:"Konoha green beast",
imageLink:"https://www.google.com/imgres?imgurl=http%3A%2F%2Fpm1.narvii.com%2F6439%2Fecfa73c34db4039a4dd92481ea16a180a18608ed_00.jpg&imgrefurl=https%3A%2F%2Faminoapps.com%2Fc%2Fnaruto%2Fpage%2Fitem%2Fmight-guy%2FpP62_LZupInrJwxPJ6ljo7bjQGaD4JvLQW&tbnid=yS1-MAqQpVQZ2M&vet=12ahUKEwiW95Dlj9v2AhXpNbcAHXJGBZQQMygJegUIARDpAQ..i&docid=F6A5JxmHTsx4zM&w=400&h=300&q=guy%20sensei&ved=2ahUKEwiW95Dlj9v2AhXpNbcAHXJGBZQQMygJegUIARDpAQ"
},
{
id:"1",
description:"again Uchiha",
imageLink:"tobi.png"
},
{
id:"2",
description:"rasenshuriken",
imageLink:"https://www.google.com/imgres?imgurl=https%3A%2F%2Fstatic.wikia.nocookie.net%2Fnaruto%2Fimages%2Fd%2Fd6%2FNaruto_Part_I.png%2Frevision%2Flatest%3Fcb%3D20210223094656&imgrefurl=https%3A%2F%2Fnaruto.fandom.com%2Fwiki%2FNaruto_Uzumaki&tbnid=8EoJhgCyc-eLmM&vet=12ahUKEwiqtLyektv2AhX7yaACHVQOB34QMygBegUIARDVAQ..i&docid=WdjV5wKAFZeaKM&w=1440&h=1076&itg=1&q=naruto&hl=en&ved=2ahUKEwiqtLyektv2AhX7yaACHVQOB34QMygBegUIARDVAQ"}
]
function Main() {
return (
<>
<Header title={"Photowall"} />
<Photowall posts = {posts}/>
</>
)
}
export default Main
I have tried through url and through statis too but it doesnot work.
Photowall.jsx
import React from 'react'
import Photo from './Photo'
function Photowall(props) {
return (
<div className='photo-grid'>
{props.posts.map((post,index) => <Photo key={index} post={post}/>)}
</div>
)
}
export default Photowall
and photo.jsx -
import React from 'react'
function Photo(props) {
const post = props.post
return (
<div>
<figure className='figure'>
<img src={post.imageLink} alt={post.description}/>
</figure>
</div>
)
}
export default Photo
please checout this repo - https://github.com/mohitRana-04/Photowall
Try copy image address and then paste it in the respective place .
const posts = [
{
id:"0",
description:"Konoha green beast",
imageLink:"should be a valid image link"
},
{
id:"1",
description:"again Uchiha",
imageLink:"should be valid image link"
},
{
id:"2",
description:"rasenshuriken",
imageLink:"should be a valid image link"}
]
The link you are passing is not a link to an Image instead it is a url to a page,
to get an Image link you have to right click and select Open image in new tab
and after that you will see this url which is an actual link to image
http://pm1.narvii.com/6439/ecfa73c34db4039a4dd92481ea16a180a18608ed_00.jpg
and this is an actual image link because it will have an extension of image at the end
I hope this will solve your problem :)

My next.js code for dynamic content and routing isn't working as expected

I'm following a YouTube tutorial for next.js and i got stuck on a very beginning point. I'm trying to create a dynamic content and routing for my website with the codes below but there is an error:
import Link from 'next/Link';
const people = [
{v: 'car', name: 'bruno'},
{v: 'bike', name: 'john'},
{v: 'airplane', name: 'mick'}
]
export default function Details (){
return <div>
{people.map( e => (
<div>
<Link as={'/${e.v}/${e.name}'} href="/[vehicle]/[person]">
<a>Navigate to {e.name}'s {e.v}</a>
</Link>
</div>
))}
</div>
}
The dynamic routing for the code above is working fine actually. But when i go to my details page, the content is looking like "${e.name}'s ${e.v}" this. It doesn't look like according to my parameters. I believe the problem occurs because of this line:
<Link as={'/${e.v}/${e.name}'} href="/[vehicle]/[person]">
I tried to change " ' " this quotation mark to this " ´ " back quote mark but that also doesn't work. Could you please help me?
I also get this error in my Developer Tools console. I changed the fb.me link for a purpose.
Warning: Each child in a list should have a unique "key" prop.
Check the top-level render call using <div>. See blablafb.me/react-warning-keys for more information.
in Link (at Details.js:13)
in Details
in App
in Unknown
in Context.Provider
in Context.Provider
in Context.Provider
in Context.Provider
in AppContainer
In your /pages/index.js file you change single quotes ' with back ticks ` to permit string interpolation, and add a key attribute to the top-level div where you map over people's array:
import Link from "next/link";
const people = [
{ v: "car", name: "bruno" },
{ v: "bike", name: "john" },
{ v: "airplane", name: "mick" }
];
export default function Details() {
return (
<div>
{people.map((e, idx) => (
<div key={idx}>
<Link href="/[vehicle]/[person]" as={`/${e.v}/${e.name}`} passHref>
<a>
Navigate to {e.name}'s {e.v}
</a>
</Link>
</div>
))}
</div>
);
}
Then create /pages/[vehicle]/[person].js where you display different content based on the link you clicked on:
import { useRouter } from "next/router";
import Link from "next/link";
export default function Person() {
const router = useRouter();
const { vehicle, person } = router.query;
return (
<div>
<p>
Vehicle: {vehicle}, Person: {person}
</p>
Go back{" "}
<Link href="/" passHref>
<a>Home</a>
</Link>
</div>
);
}

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.

What is the best way to do a route in next.js

I'm a bit of a beginner at javascript but I am using next routes which uses path-to-regexp under the hood.
I have a page that has a list of links. The route for this page is /locations/s-:specialty-providers with "specialty" being the only dynamic part.
When I click on one of the links on the page, it reroutes me to /locations/s-s-:specialty-providers/:abbr (where both specialty and abbr are dynamic) when it should be rerouting to /locations/s-:specialty-providers/:abbr.
Routes file:
{
name: 'sitemap-providers-location-procedure',
page: 'sitemap/providers/by_location/by_procedure',
pattern: '/locations/:procedure-providers'
},
{
name: 'sitemap-specialties-location-city',
page: 'sitemap/specialties/by_location/by_city',
pattern: '/locations/s-:specialty-providers/:abbr'
},
Next.js will give you routing out of the box with putting your file in pages directory
Let's say you have pages/index.js
import Link from 'next/link'
function getSitemaps () {
return [
{
id:"1",
title: "sitemap-providers-location-procedure",
s: "providers",
abbr: "by_procedure",
},
{
id:"2",
title: "sitemap-specialties-location-city",
s: "specialties",
abbr: "by_city",
}
]
}
const SitemapLink = ({post}) => (
<li>
<Link as={`/sitemap/${post.s}/by_location/${post.abbr}`} href={`/sitemap?title=${post.title}`}>
<a>{post.title}</a>
</Link>
</li>
)
export default () => (
<div>
<h1>Links</h1>
<ul>
{getSitemaps().map((sitemap) => (
<SitemapLink key={sitemap.id} post={sitemap}/>
))}
</ul>
</div>
)
and there is another filepages/sitemap.js
import {withRouter} from 'next/router'
const Page = withRouter((props) => (
<div>
<h1>{props.router.query.title}</h1>
<p>This is the page content.</p>
</div>
))
export default Page
Now you have that dynamic routes.
You don't need any magic or pattern in next.js to create route.

Categories

Resources