'Cannot Find Module' when using an Image in React - reactjs

I am using React and I am running into an issue importing images in a component. Now I know how to use the import method, which is fine for some things but in this case the image src is part of an array of objects I need to map over.
So let me start with if I do this directly: <img src={require('../../images/leadinvestigator.jpg')} /> It works just fine.
However if I do this: <img src={require(member.image)} /> or <img src={require(${member.image})} /> I get:
react-dom.development.js:11340 Uncaught Error: Cannot find module '../../images/leadinvestigator.jpg'
and if I do this: <img src={require({member.image})} /> I get an invalid token error
here is my component code:
import React from "react"
import "react-responsive-carousel/lib/styles/carousel.min.css"
import { Carousel } from 'react-responsive-carousel'
import './styles.css'
const Crew = () => {
const crewMembers = [
{
image: '../../images/leadinvestigator.jpg',
name: 'Bryant Richards',
title: 'Lead Investigator',
quote: 'In the end, it only matters what you believe'
}
]
return (
<Carousel
showArrows={true}
infiniteLoop={true}
showThumbs={false}
showStatus={false}
autoPlay={true}
interval={6100}
>
{
crewMembers ? crewMembers.map(member => (
<div>
<img src={require('../../images/leadinvestigator.jpg')} />
<div className="myCarousel">
<h3>{member.name}</h3>
<h4>Designer</h4>
<p>
It's freeing to be able to catch up on customized news and not be
distracted by a social media element on the same site
</p>
</div>
</div>
)) : null
}
</Carousel>
)
}
export default Crew

Try to import your image before put it in the object.
Add on top of your component:
import bryantImage from '../../images/leadinvestigator.jpg'
and then add this image to your object like that:
const crewMembers = [
{
image: bryantImage,
name: 'Bryant Richards',
title: 'Lead Investigator',
quote: 'In the end, it only matters what you believe'
}
]

Related

Can I reference component props to get from parent when I am supposed to provide child component with props?

I am working o a project with multiple carousels.
so I decided to create a carouselitem.js component, a carousel.js component that includes multiples item component slides, a slides.js files with all items data.
the idea is to provide data about carousel slides in slides.js file then map them to the item component so when an object in added to the file it gets automatically to the carousel.
import Carousel from "react-bootstrap/Carousel";
function Carouselslideitem(props) {
return (
<Carousel.Item>
<img className="d-block w-100" src={props.image} alt={props.alter} />
<Carousel.Caption>
<h3>{props.header}</h3>
<p>{props.description}</p>
</Carousel.Caption>
</Carousel.Item>
);
}
export default Carouselslideitem;
above is the item component as you see it is supposed to get props parent component carouselslide.js which is defined as follows
import Carousel from "react-bootstrap/Carousel";
import Carouselslideitem from "./Carouselslideitem.js";
function Carouselslider(props) {
return (
<Carousel fade>
{props.list.map((e) => {
return (
<Carouselslideitem
image={e.slide}
alter={e.alter}
header={e.header}
description={e.description}
/>
);
})}
</Carousel>
);
}
export default Carouselslider;
this is the slide.js files containing the carousel data
[enter image description here][3]
const image1 = "../images/homeslider/1.png";
const image2 = "../images/homeslider/2.png";
const image3 = "../images/homeslider/3.png";
const slides = [
{
slide: image1,
alter: "slide1",
header: "Header1",
description: "Desc 1",
},
{
slide: image2,
alter: "slide 2",
header: "header2",
description: "desc2",
},
{
slide: image3,
alter: "slide3",
header: "header3",
description: "desc3",
},
];
export default slides;
and finally the app.js component
import Navigationbar from "./components/Navbar";
import Carouselslider from "./components/Carouselslider";
import slides from "./components/slides.js";
function App() {
return (
<div className="App">
<Navigationbar />
<Carouselslider list={slides} />
</div>
);
}
export default App;
the things that makes worry is whether I will be able to pass the list props from app.js to carouselslideitem.js through carouselslide.js
To sum it up, I am trying to import the data from slides.js to the app.js component and pass it as list props to carouselslide.js which uses the data and maps it to carouselslideitem.js component and display a slide for each object represented on slides.js
I am thinking this way I will be able to create a carousel for each data fileps: I am currently getting this errors from the console(see screenshot!)
I hope the code is clear and easy to read.
and thank you.

Image not getting displayed when using Reactjs map function. Error--SRC undefined

Here's the error:
Everything else gets displayed well instead of my image. I am using image which saved in my local computer and I'm getting no error in VC editor console. I get error in developer tools console.
./card/index.jsx
import React from 'react'
const Card = (props) => {
console.log(props);
return (
<div className="wrapperDiv">
<img src={props.img} alt={props.alt}/>
<p>{props.desc}</p>
<button>{props.value}</button>
</div>
)
}
export default Card
./reports/index.jsx
import React from 'react';
import Card from './Card';
import Data from './Card/data';
function createCard(Data){
return <Card
src={Data.src}
alt={Data.alt}
desc={Data.desc}
value={Data.value}
/>
}
const Reports = () => {
return (
<div className="reportsDiv">
{ Data.map(createCard)}
</div>
)
}
export default Reports
data file
import img1 from "./img.jpg";
const Data=[
{
id:1,
img:"{img1}",
alt:"helloworld",
desc:"Sdfasdf",
value:"5GB"
},
{
id:2,
img:{img1},
alt:"helloworld",
desc:"Sd",
value:"35GB"
},
{
id:3,
img:{img1},
alt:"helloworld",
desc:"asdf",
value:"3GB"
}
]
export default Data;
It works if I give value in card component like this:
{/* <Card
img={img1}
alt="helloworld"
desc="System Junk"
value="35GB"
/>
<Card
img={img1}
alt="helloworld"
desc="Sdfasdf"
value="35GB"
/>
<Card
img={img1}
alt="helloworld"
desc="vhghhjghjg"
value="35GB"
/>
*/}
But src is coming undefined if I use map function. Please help. Thanks in advance for help.
Note your createCard function which you're sending src as the image source :
function createCard(Data){
return <Card
src={Data.src}// you're sending src as the prop
alt={Data.alt}
desc={Data.desc}
value={Data.value}
/>
}
But you will use img as the source in the Card component:
const Card = (props) => {
console.log(props);
return (
<div className="wrapperDiv">
<img src={props.img} // but using img as the prop which is incorrect
alt={props.alt}/>
<p>{props.desc}</p>
<button>{props.value}</button>
</div>
)
}
Change the Card to the bellow will solve the problem:
const Card = (props) => {
console.log(props);
return (
<div className="wrapperDiv">
<img src={props.src} // change it to src
alt={props.alt}/>
<p>{props.desc}</p>
<button>{props.value}</button>
</div>
)
}

next/image not working with props as image source

My Home page sends data from my strapi cms to my PostSlider component via props
import React from "react";
import styles from './index.module.scss'
import { AxiosService } from '../utils/axios-service'
import PostSlider from '../components/postSlider/postSlider'
const Home = ({ posts }) => {
return (
<div id='contentsWrap' className={styles.dohandsWrap}>
<PostSlider home={true} posts={posts} />
</div>
)
}
export default Home
export async function getStaticProps() {
const axios = AxiosService.create()
const res = await axios.get('/archives', {
params: {
category: 'news',
display: true,
showDoson: true,
_limit: 5,
_sort: 'id:DESC'
}
})
return {
props: {
posts: res.data,
},
}
}
My postSlider component then maps over the data to fill my slider
import React from "react";
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import styles from './postSlider.module.scss'
import Link from 'next/link'
import Image from 'next/image'
export default function PostSlider({ home, posts }) {
var settings = {
infinite: posts.length > 2 ? true : false,
autoplay: false,
speed: 500,
autoplaySpeed: 3000,
slidesToShow: 3,
slidesToScroll: 1,
};
return (
<section className={`${styles.postSlider} postSlider ${home ? styles.postSliderHome : 'postSliderNotHome'} ${posts.length > 2 ? 'postSliderPadding' : ''}`}>
<Slider {...settings}>
{posts.map((post) => {
const date = new Date(post.displayDate);
return (
<Link key={post.id} href={`/news/${post.id}`}>
<a className={styles.postSliderLink}>
<article>
<Image src={post.images[0]?.url} alt={post.images[0]?.alternativeText} width={376} height={190} layout="fixed" />
</article>
</a>
</Link>
)
})}
</Slider>
</section>
);
}
I made sure to include my cdn address in module.exports in next.config.js but I get the following error
Error: Image is missing required "src" property. Make sure you pass
"src" in props to the next/image component. Received:
{"width":376,"height":190}
If I remove the next/image component for the normal img tag, everything works fine.
What am I doing wrong?
Well, it seems like one of your posts have empty images array?
Image component is required to have src property and you pass undefined instead.
You can check if there is at least one image and then render it, like that:
<article>
{post.images.length > 0 && (
<Image src={post.images[0].url} alt={post.images[0].alternativeText} width={376} height={190} layout="fixed" />
)}
</article>
Try before the return:
const src = {src: post.images[0]?.url}
Then inside the return:
<Image {...src} //etc...
Sometimes, the <Image /> tag doesn't work like it should and doesn't accept the src . Try defining the URL before return and then pass the URL in the src property.
Just before return:
const url = post.images[0]?.url;
And then you can add:
<Image src={url} alt={post.images[0]?.alternativeText} width={376} height={190} layout="fixed" />

Caching in Gatsby JS

I have this Gatsby app where when I visit home page everything loads at first including the Testimonials section. However, when I visit another page, for instance the Blog list page and then click on the link back to homepage the data on Testimonials component won't load and you will see a blank area of the app where the Testimonials section is placed. In order to see the Testimonials list, you will have the refresh the page again.
For the record the data on my Testimonials component are being pulled out on Strapi JS that is deployed on Heroku.
So far I got this on my index.js:
import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/Layout"
import Header from "../components/Header"
import Testimonials from '../components/Testimonials'
import Blogs from '../components/Blogs'
import SEO from '../components/SEO'
export default function Home({ data }) {
const {
allStrapiBlogs: { nodes:blogs },
} = data
return (
<>
<SEO />
<div className="main-container">
<Layout>
<Header />
<Testimonials title="Testimonials" />
<Blogs title="Latest Blogs" blogs={blogs} showAllBlogLinks/>
<Map />
</Layout>
</div>
</>
)
}
export const query = graphql`
{
allStrapiBlogs(filter: {featured: {eq: true}}, sort: {fields: published_date, order: DESC}, limit: 6) {
nodes {
id
title
content
slug
published_date(formatString: "MMMM DD, YYYY")
featured_image {
childImageSharp {
fluid {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`
And then on my Testimonials.js component:
import React from "react"
import { graphql, useStaticQuery } from "gatsby"
import Image from "gatsby-image"
import { FaStar } from "react-icons/fa"
import Title from './Title'
const query = graphql`
{
allStrapiTestimonials {
nodes {
id
name
cite
text
photo {
childImageSharp {
fluid{
...GatsbyImageSharpFluid_withWebp
}
}
}
}
}
}
`
const Testimonials = ({ title }) => {
const data = useStaticQuery(query)
const { allStrapiTestimonials: { nodes:testimonials } } = data
return (
<div className="testimonial-section section-padding" id="testimonial" data-aos="zoom-in">
<div className="container">
<div className="row">
<div className="col-lg-12">
<div className="section-title-two center">
<Title title={title} />
</div>
</div>
</div>
<div className="testimonial-wrap row">
<div className="testimonial-slider owl-carousel">
{ testimonials.map(item => {
const { id, name, cite, text, photo } = item
return(
<div className="col-xl-8 col-lg-10 col-12 ml-auto mr-auto" key={id}>
<div className="testimonial-item mt-40">
<div className="testimonial_img">
<Image fluid={photo.childImageSharp.fluid} alt={name} style={{ position: "absolute", overflow: "visible", display: "block", width: "211px", height: "207px" }} />
</div>
<div className="testimonial_content xs-mt-40">
<div className="testimonial_content_item mb-30">
<div className="testimonial_content__pro">
<h4 className="mb-10">{ name }</h4>
<p>{ cite }</p>
</div>
<ul className="d-none d-sm-inline-block">
<li><FaStar></FaStar></li>
<li><FaStar></FaStar></li>
<li><FaStar></FaStar></li>
<li><FaStar></FaStar></li>
<li><FaStar></FaStar></li>
</ul>
</div>
<div>
<p>{ text } </p>
</div>
</div>
</div>
</div>
)
})}
</div>
</div>
</div>
</div>
)
}
export default Testimonials
Any idea what's causing this error? How can I fix it?
I've faced a similar issue a few months ago and the fix depends strictly on the implementation and your code. Basically, what is happening is that React's doesn't understand that he needs to rehydrate some components because pointing to some global objects as window or document of the DOM, outside the React's ecosystem (without using states) may block that rehydration, in your cause, because of jQuery.
All the possible solutions that bypass this issue will be patches (like trying to add the cache). The ideal solution would avoid using jQuery, which points directly to the DOM, with React, which manipulates the virtual DOM (vDOM).
There's nothing wrong with the code you've shared, however, based on some other questions that you did, you are using jQuery and using the window object, which prevents the rehydration of some React components. You should get rid of jQuery or using some React-based approach. Something like this should do the trick to force a loader across the whole site:
const Layout = ({ children }) => {
const [loader, setLoader]=useState(true);
useEffect(()=>{
setTimeout(()=> {
setLoader(false)
}, 400)
}, [])
return <section className={`site__wrapper`}>
<Header />
<main>{loader ? <Preloader/> : children}</main>
</section>;
};

can't Load local files dynamically in react js

I want to load some local images dynamically in my app. I have a json with records like
{name: image12, poster: 'image1.jpg'}, {name: image13, poster: 'image2.jpg'}
I have a folder with many images like 'image1.jpg', 'image2.jpg', 'image3.jpg'. When I try to render the json record i put
<img src={'./image/image1.jpg'}/> but it is not working.
[![import React from 'react';
const Poster = (props) => {
return(
<div className="individual-poster">
<h2>{props.postData.name}</h2>
<img src={'./Slices/'+props.postData["poster"]} width="100px" height="100px"/>
</div>
);
}
image is not even listing in the source list also.
if you know path images then your json object you trying to map must be somewhat similar to this:
const obj = [
{"name":"Chrysanthemum","path":require('./Chrysanthemum.jpg')}, //this will work
{"name":"Desert","path":'./Desert.jpg'}, //will not work
]
require your path to images must be inside require mehtod.
Use like considering json obj file exported as default in same directory with file name imagesJson.
import imagArray from './images';
map like this
imagArray.map((m)=>{
return <div>
{m.name}
<img src={m.path}/>
</div>
})
If you created you react app with create-react-app then you can import image variable and later use it multiple time.
import logo from './logo.png' // relative path to image
class App extends Component {
render() {
return (
<img src={logo} alt={"logo"}/>
)
}
}
or you can directly specify image relative path.
<img src ="http://localhost:3000/img/foo.png" />
<img src="/details/img/bar.png" />
In your question for use images from array
const images = [{
name: 'image12',
path: 'image1.jpg'
}, {
name: 'image13',
path: 'image2.jpg'
}];
class App extends Component {
render() {
return (
<div>
<img src={logo} alt={"logo"}/>
{images.map((img) => <img src={img.post} alt={img.name} />)}
</div>
)
}
}

Resources