Cannot use images with props in React - javascript

I'm trying to send an image as a prop from
import React from "react";
import "./home.css";
import Product from "./Product";
function Home() {
return (
<div className="home">
<div className="home-container">
<img
className="home-image"
src={require("./nathan-oakley-gj1dnc7yRG0-unsplash.jpg")}
alt=""
/>
<div className="home-row">
<Product
title="Sofa Couch"
price={5000}
image={"./phillip-goldsberry-fZuleEfeA1Q-unsplash.jpg"}
rating={5}
/>
<Product />
</div>
<div className="home-row">
<Product />
<Product />
<Product />
</div>
<div className="home-row">
<Product />
<Product />
</div>
</div>
</div>
);
}
export default Home;
in the home-row class to
import React from "react";
import "./product.css";
function Product({ title, image, price, rating }) {
return (
<div className="product">
<div className="product-info">
<p>{title}</p>
<p>
<small>$</small>
<strong>{price}</strong>
</p>
<div className="product-rating">
{Array(rating)
.fill()
.map((_, i) => (
<p>*</p>
))}
</div>
</div>
<img src={require(`${image}`)} alt="" />
<button>Add to Basket</button>
</div>
);
}
export default Product;
this file. But the image is not showing. Even if I remove require it doesn't show up.
Earlier I was using a local image and it was working with require. But this doesn't.
When I inspect it with console, it says uncaught error, cannot find module 'image name'.

Related

react error: "TypeError: Cannot read properties of undefined (reading 'props')"

I am trying to make a popUp for each of my gallery items containing some information on the picture. Clicking on the picture and showing the pop up works fine, but I can't close it. I get the error that can be read in the title. I understand that there probably is an error regarding the sending of the "setButtonPopUp", but I couldn't understand it yet.
PopUp.js
import React from "react";
import "./PopUp.css";
export default function PopUp(props) {
return props.trigger ? (
<div className="popUpWrapper">
<div className="popUp">
<button
className="closePopUp"
onClick={onClick={props.setTrigger}}
>
close
</button>
{props.children}
</div>
</div>
) : (
""
);
}
GalleryItem.js
import "./GalleryItem.css";
import TextItem from "../TextItem/TextItem.js";
import AlertMessage from "../alertMessage.js";
import PopUp from "../PopUp/PopUp.js";
import { useState } from "react";
export default function GalleryItem({ itemData }) {
const [buttonPopUp, setButtonPopUp] = useState(false);
if (itemData.polaroid === "light") {
return (
<div
className="itemContainer"
onClick={() => setButtonPopUp(true)}
>
<PopUp trigger={buttonPopUp} setTrigger={() => {
setButtonPopUp(false);
}}>
<h3>Info</h3>
<p>{itemData.info}</p>
</PopUp>
<img className="clip" src="../../assets/klammer.png" alt="" />
<img className="polaroid" src="../../assets/polaroid.png" alt="" />
<img className="image" src={itemData.src} alt="" />
<h2 className="polaroidTitleLight">{itemData.title}</h2>
</div>
);
} else if (itemData.polaroid === "dark") {
return (
<div
className="itemContainer"
onClick={() => AlertMessage(itemData.info)}
>
<img className="clip" src="../../assets/klammer.png" alt="" />
<img className="polaroid" src="../../assets/polaroid_dark.png" alt="" />
<img className="image" src={itemData.src} alt="" />
<h2 className="polaroidTitleDark">{itemData.title}</h2>
</div>
);
} else {
return <TextItem itemData={itemData} />;
}
}
What I did notice is that if I try to use the PopUp Component directly in App.js, the PopUp works just fine. But If I try to use it in SiteChanger it's not working anymore. This is the App.js:
App.js
import "./App.css";
import Header from "../Header/Header.js";
import SiteChanger from "../changeSite/changeSite.js";
function App() {
return (
<div>
<Header />
<SiteChanger />
</div>
);
}
export default App;
All help would be greatly appreciated!
You're not sending the prop setTrigger here:
<div
className="itemContainer"
onClick={() => setButtonPopUp(true)}
setTrigger={setButtonPopUp} // Should go to down PopUp
>
<PopUp trigger={buttonPopUp}>
<h3>Info</h3>
<p>{itemData.info}</p>
</PopUp>
Also, there's no this in functional components. It's just props. Here's the solution:
<button
className="closePopUp"
onClick={() => props.setTrigger(false)}
//---------------^^^^^ // Update this
>
Send the props to correct component and not <div>:
<div
className="itemContainer"
onClick={() => setButtonPopUp(true)}
// setTrigger={setButtonPopUp} // Remove this and...
>
<PopUp trigger={buttonPopUp} setTrigger={setButtonPopUp}> // Add here.
<h3>Info</h3>
<p>{itemData.info}</p>
</PopUp>

Next js component doesn't show without reload

Basically, I have a nested component that I want to render with the parent component and it's working fine when the server starts.
But the problem arises when I switch back from another page. Some of the nested components get disappeared. If I made a refresh then again everything ok.
How can I solve this issue?
Normal:
Image-1
Component disappeared:
Image-2
Index.js:
import BannerBaseLine from "./../components/HOME/Banner/BannerBaseLine";
import SubSection1 from "./../components/ABOUT/subSection1";
import CoursesList from "../components/HOME/MOSTTRENDING/CoursesList/courseslist";
import ShortOverview from "./../components/HOME/CourseOverviewSection/Section1/shortoverview";
import Testimonial from "./../components/HOME/Testimonial/testimonial";
import ClientItem from "./../components/HOME/Client-area/all-client-item";
export default function HomeMain({categories}) {
return (
<>
<br></br>
<br></br>
<br></br>
<BannerBaseLine categories = {categories} />
<CoursesList />
{/* <SubSection1 /> */}
<ShortOverview />
<CoursesList />
<Testimonial />
<ClientItem />
</>
);
}
export async function getStaticProps(){
const response = await fetch('http://localhost:8000/api/data/categories')
const data = await response.json()
console.log(data)
return {
props:{
categories : data,
}
}
}
BannerBaseLine component:
import BannerBlock from './BannerBlock';
export default function BannerBaseLine({ categories }) {
return (
<>
<section
className="banner-area"
style={{ backgroundImage: "url(assets/img/banner/0.jpg)" }}
>
<div className="container">
<div className="row">
<div className="col-lg-6 col-md-8 align-self-center">
<div className="banner-inner text-md-start text-center">
<h1>
Find the Best <span>Courses</span> & Upgrade{" "}
<span>Your Skills.</span>
</h1>
<div className="banner-content">
<p>
Edufie offers professional training classes and special
features to help you improve your skills.
</p>
</div>
<div className="single-input-wrap">
<input type="text" placeholder="Search your best courses" />
<button>
<i className="fa fa-search"></i>
</button>
</div>
</div>
</div>
</div>
</div>
</section>
<br></br>
<br></br>
<div className="container">
<div className="intro-area-2">
<div className="row justify-content-center">
<div className="col-lg-12">
<div className="intro-slider owl-carousel">
{categories.map((category) => {
return (
<>
<BannerBlock category={category} key={category.id} />
</>
);
})}
</div>
</div>
</div>
</div>
</div>
</>
);
}
BannerBlock component:
export default function BannerBlock({category}) {
console.log(category);
return (
<div className="item">
<div className="single-intro-wrap">
<div className="thumb">
<img src={category.image} alt="img" />
</div>
<div className="wrap-details">
<h6>
{category.Base_Category_Title}
</h6>
<p>236 Course Available</p>
</div>
</div>
</div>
);
}
From https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation
Note: You should not use fetch() to call an API route in
getStaticProps. Instead, directly import the logic used inside your
API route. You may need to slightly refactor your code for this
approach.
Fetching from an external API is fine!
you should check if categories exist
export default function HomeMain({categories}) {
if(categories){
return <Loading Component />
}
rest of the code...
}

how to use background image using props using reactjs

here is my code where i'm trying to pass object like{title,description,backgroundImg ....} to section component using props , I am getting all the key & value but when I use it on section component getting all data value instead of backgroundImg why..?
import React from "react";
import Section from "./Section";
function Home() {
return (
<div>
<div className="container">
<Section
title="Model S"
description="Order Online for Touchless Delivery"
backgroundImg="model-s.jpg"
leftButton="custom order"
rightButton="existing inventory"
/>
<Section
title="Model Y"
description="Order Online for Touchless Delivery"
backgroundImg="../images/model-y.jpg"
leftButton="custom order"
rightButton="existing inventory"
/>
</div>
);
}
export default Home;
to
import React from "react";
import DownArrow from "../images/down-arrow.svg";
const Section = (props) => {
return (
<div
className="Wrap"
style={{ backgroundImage: `url(${props.backgroundImg})` }}
>
<div className="item_text">
<h1>{props.title}</h1>
<p>{props.description}</p>
</div>
<div className="">
<div className="item_buttom">
<div className="leftButton">{props.leftButton}</div>
<div className="RightButton">{props.rightButton}</div>
</div>
<div>
<img src={DownArrow} alt="svgImg" className="DownArrow" />
</div>
</div>
</div>
);
};
export default Section;
My image folder path is "../images/..."
You need to import image in your home component.
Like
import sectionImage from "../images/image.jpg";
then pass the image like
<Section
backgroundImg={sectionImage}
/>
Then it should work fine.

Why can't I import a React component from a file?

I think I have written all the code right, but on the port I can only display app.js file
import React from 'react';
import ImgSlider from './ImgSlider';
import './App.css';
function App() {
return (
<div className="App" >
<div className="book-box">
<img src="" alt=""/>
<div>
<h1>Harry Potter</h1>
</div>
</div>
</div>
);
}
export default App;
and I want to import div element from ImgSlider
import React from 'react';
function ImgSlider() {
return (
<div>
<h3>Heading</h3>
<p>Description</p>
<img src="" alt=""/>
</div>
);
}
export default ImgSlider;
When i open browser it only shows HARRY POTTER from the App.js, I think it should also display div from the ImgSlider
Console massage Line 3:8: 'ImgSlider' is defined but never used no-unused-vars
Thanks for the attention
You arent rendering ImgSlider, just need to do this in App.js:
function App() {
return (
<div className="App" >
<div className="book-box">
<img src="" alt=""/>
<div>
<h1>Harry Potter</h1>
/* ADD this code*/
<ImgSlider />
</div>
</div>
</div>
);
}
This is just an example, you can add the <ImgSlider/> wherever you want.
To render some content from imported component you have to render it like:
return (
<div className="App" >
<div className="book-box">
<img src="" alt=""/>
<div>
<h1>Harry Potter</h1>
{/*Place it where you want to show it */}
<ImgSlider />
</div>
</div>
</div>
);
}
Simply add <ImgSlider /> into App
Your final code would look like this:
import React from 'react';
import ImgSlider from './ImgSlider';
import './App.css';
function App() {
return (
<div className="App" >
<div className="book-box">
<img src="" alt=""/>
<div>
<h1>Harry Potter</h1>
<ImgSlider />
</div>
</div>
</div>
);
}
export default App;

Component not loading when route changed

I am using Preact. I first tried preact-router then wouter for routing, but the problem still exists for one specific component. Here is the main entry where all routes defined:
import { h, Component } from 'preact';
import { Route } from "wouter-preact";
import Header from './partials/header';
import Home from './pages/home';
import News from './pages/news';
import Article from './pages/article';
export default class App extends Component {
render() {
return (
<div id="app">
<Header />
<Route path="/"><Home /> </Route> // working perfectly
<Route path="/a/:article"> <Article /> </Route> // not working
<Route path="/n/:newspaper"><News /> </Route> // working
</div>
);
}
}
and here is the simplified second component which is working perfectly :
import { h, Fragment } from 'preact';
import { Link, Route } from "wouter-preact";
import useFetch from '../../utils/ajax';
export default function News() {
const url = window.location.pathname.split('/');
const { data, loading } = useFetch(domain + '/api/v1/news/?newspaper=' + url[2]);
return (
<Fragment>
{loading ? (
// loading indicator
) : (
<main role="main">
<div className="py-5">
<div className="container">
<div className="row">
{data.results.map((nisha, index) => (
<div className="col-sm-6" key={index}>
<div className="col-md-10" >
<div className="card mb-2 shadow-lg" style={{ border: 'none' }} >
<Link href={'/a/' + nisha.slug}>
<img className="card-img-top" src={ nisha.cover_image } alt={ nisha.slug } />
</Link>
<div className="card-body">
// body
<div className="card-footer text-muted">
// footer
</div>
</div>
</div>
</div>
</div>
))}
</div>
</div>
</div>
</main>
)}
</Fragment>
);
}
and finally the problematic component, when I click any link from previous component, browser url changing but the component is not loading (there is no debug console message in browser console).
export default function Article() {
console.log("loaded");
return (
<div className="main">
<div className="py-5">
<div className="column">
<div>example article</div>
</div>
</div>
</div>
);
}

Categories

Resources