Browser URL updates but components do not update - reactjs

I have a problem. Link in component change Url in browser but not return component until i reload my browser.
I click product detail. Inside product detail have similar product.
I click on product details of similar products.
-> Browser Url update but it doesn't return product details until I reload the browser.
This is product in home:
<div className="col-md col-6">
<figure className="card-product-grid card-sm">
<Link to={`product-detail/${item.id}`} className="img-wrap item">
<img src={img_path + item.image} alt="null" />
</Link><div className="text-wrap p-3">{item.productName}
<span className="badge badge-danger"> {item.salePrice * 100 / item.price}
</span>
</div>
</figure>
</div>
This is similar product:
{productLike && productLike.length > 0 && productLike.map((item, index) => {
return <>
<Product key={index} id={item.id} image={item.image} productName={item.productName} detail={item.detail} price={item.price} />
This is Product component:
import React from "react";
import { Link } from "react-router-dom";
class Product extends React.Component {
render() {
var img_path = "http://localhost:8000/img/"
return (
<div class="col-md-3">
<figure class="card card-product-grid">
<div class="img-wrap">
<img src={img_path + this.props.image} alt="null" />
</div>
<figcaption class="info-wrap">
<h6 class="title" >{this.props.productName}</h6>
<Link to={`/product-detail/${this.props.id}`} class="title mb-2">{this.props.detail.indexOf('</') !== -1
? (
<div dangerouslySetInnerHTML={{ __html: this.props.detail.replace(/(<? *script)/gi, 'illegalscript') }} >
</div>
)
: this.props.detail
}</Link>
<div class="price-wrap">
<span class="price">{this.props.price}</span>
<small class="text-muted">/per bag</small>
</div>
<p class="mb-2"> 2 Pieces <small class="text-muted">(Min Order)</small></p>
<p class="text-muted ">Guangzhou Yichuang Electronic Co</p>
<hr />
<label class="custom-control mb-3 custom-checkbox">
<input type="checkbox" class="custom-control-input" />
<div class="custom-control-label">Add to compare
</div>
</label>
<i class="fa fa-envelope"></i> Contact supplier
</figcaption>
</figure>
</div>
);
}
}
export default Product;
Can someone help? Thank!

Related

Image does not load in react

I am trying to load an image to a react web app. Here is the code.
export default function Card(props) {
return (
<div className="card">
<img src={`./${props.img}`} alt="Ngong hills image" className="card--image" />
<div className="card-stats">
<img src={Star} className="card--star" />
<span>5.0</span>
<span className="gray">(6) • </span>
<span className="gray">KEN</span>
</div>
<p>Visit Ngong with Stephen Muchendu</p>
<p>
<span className="bold">From $100</span>
</p>
</div>
);
}
However, the image does not load. What could be the problem?
export default function Card(props) {
return (
<div className="card">
<img src={props.img} alt="Ngong hills image" className="card--image" />
<div className="card-stats">
<img src={Star} className="card--star" />
<span>5.0</span>
<span className="gray">(6) • </span>
<span className="gray">KEN</span>
</div>
<p>Visit Ngong with Stephen Muchendu</p>
<p>
<span className="bold">From $100</span>
</p>
</div>
);
}

Sending request to elasticsearch using axios to map cards

I have a frontend react app that have cards, search bar, and filters. So to map the cards that I have, I want to send a request to elasticsearch (port:9200) using axios to save all the data in array and map my cards as I want, can you please help me?
Edit: I update the code here and include all of it, but there is no card mapped
function CreateCards(NCARMap) {
return(
<SimpleCard
key={NCARMap.id}
theCardId={NCARMap.id}
cardType={NCARMap.approvetool}
cardNum={NCARMap.num}
cardName={NCARMap.name}
cardDate={NCARMap.date}
// cardCategory={NCARMap.cardCategory}
// cardSource={NCARMap.cardSource}
cardDesc={NCARMap.summary}
cardURL={NCARMap.image}
/>
);
}
//create the class
export default class OfficialDocument extends Component {
constructor(props) {
super(props);
this.state = {
NCARMap: [],
NCARMapAS: [],
};
}
componentDidMount(){
//Get NCARMap data, NCARMapAS used for filtring and sorting the cards
axios.get('http://localhost:9200/ncar_index/ncar/_search')
.then(resp => {
console.log(resp)
this.setState({
NCARMap: resp._source,
NCARMapAS:resp.data
})
console.log(this.state.NCARMap)
})
}
handleChange(event) {
const search_query = event.target.value;
}
render(){
return(
//HTML FILE Converted to React
<div>
<meta charSet="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta httpEquiv="X-UA-Compatible" content="ie=edge" />
<title>منشآت</title>
<link rel="shortcut icon" href="/images/favicon.png" type="image/x-icon" />
{/*============= ScrollToTop Section Starts Here =============*/}
<div className="overlayer" id="overlayer">
<div className="loader">
<div className="loader-inner" />
</div>
</div>
<i className="fas fa-angle-up" />
<div className="overlay" />
{/*============= ScrollToTop Section Ends Here =============*/}
{/*============= Header Section Starts Here =============*/}
<header className="header-section">
<div className="container">
<div className="header-wrapper">
<div className="logo-area">
<div className="logo">
<a href="/">
<img src="/images/logo/logo.png" alt="logo" />
</a>
</div>
<div className="support headFont">
الصفحة الرئيسية
</div>
</div>
<ul className="menu headFont">
<li>
{/*Here we need to change the herf link*/}
الوثائق و المحفوظات
</li>
<li>
الأخبار
</li>
<li>
{/*Here we need to change the herf link*/}
التغريدات
</li>
{/*Here we need to change the herf link*/}
{/* I want to know the diffrence between the two below */}
<li className="d-md-none text-center">
تسجيل دخول
</li>
</ul>
<div className="header-bar d-lg-none">
<span style={{backgroundColor: '#00A7CF'}} />
<span style={{backgroundColor: '#00A7CF'}} />
<span style={{backgroundColor: '#00A7CF'}} />
</div>
{/* <div class="header-right"> */}
{/*Here we need to change the herf link*/}
{/* تسجيل دخول
</div> */}
</div>
</div>
</header>
{/*============= Header Section Ends Here =============*/}
{/*============= Banner Section Starts Here =============*/}
<section className="banner-2 bg_img" data-background="/images/banner/background3.png">
<div className="container">
<div className="banner-content-2">
<h1 className="title cl-white">مرحباً بك في قسم الوثائق والمحفوظات</h1>
<p className=" cl-white">يحتوي هذا القسم على الوثائق والمحفوظات المعتمدة من المركز الوطني للوثائق والمحفوظات</p>
<form className="search-form round">
<input type="text" style={{textAlign: 'right', color: 'black'}} placeholder="... ابحث هنا" />
<button type="submit"><i className="flaticon-search" /> <span className="d-none d-sm-inline-block">ابحث</span></button>
</form>
</div>
</div>
</section>
{/*============= Banner Section Ends Here =============*/}
{/*============= How Search Section Starts Here =============*/}
<div className="how-search-section padding-bottom mt--93">
<div className="container">
<div className="row mb-30-none justify-content-center">
<div className="filter-rtl">
{/*begin::Body*/}
<div className="card-body filters">
{/*begin::Form*/}
<form>
{/*begin::Categories*/}
<div className="form-group mb-11">
<label className="font-size-h3 font-weight-bolder text-dark mb-7">التنصيفات</label>
{/* start dropdown menue */}
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
أداة الاعتماد
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">أمر ملكي</a>
<a class="dropdown-item" href="#">مرسوم ملكي</a>
<a class="dropdown-item" href="#">قرار مجلس الوزراء</a>
<a class="dropdown-item" href="#">أمر سامي</a>
<a class="dropdown-item" href="#">قرار وزاري</a>
<a class="dropdown-item" href="#">قرار مجالس وهيئات</a>
<a class="dropdown-item" href="#">قرار إداري</a>
<a class="dropdown-item" href="#">توجيه سامي</a>
</div>
</div>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
فئة الوثيقة
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">الاتفاقيات و المعادات الدولية العامة</a>
<a class="dropdown-item" href="#">الاتفاقيات الدولية الثنائية</a>
<a class="dropdown-item" href="#">الاتفاقيات الدولية متعددة الأطراف</a>
</div>
</div>
</div>
{/* end dropdown menue */}
{/* Start: : DateRangePickerComponent */}
<DateRangePickerComponent></DateRangePickerComponent>
{/* End: : DateRangePickerComponent */}
{/*end::Categories*/}
<button type="submit" className="btn btn-primary font-weight-bolder mr-2 px-8">إعادة ضبط</button>
<button type="reset" className="btn-submit btn btn-clear font-weight-bolder text-muted px-8">بحث</button>
</form>
{/*end::Form*/}
</div>
{/*end::Body*/}
</div>
<div className="general-card">
{this.state.NCARMap.map(CreateCards)}
{console.log(this.state.NCARMap)}
</div>
</div>
</div>
</div>
{/*============= How Search Section Ends Here =============*/}
{/*============= Footer Section Starts Here =============*/}
<footer className="footer-section pt-70-145">
<div className="dot-slider bg_img" />
<div className="container">
<div className="row mb--50 justify-content-between">
<div className="col-sm-8 col-lg-4">
<div className="footer-widget widget-about">
</div>
</div>
</div>
</div>
<div className="footer-bottom cl-white">
<p>جميع الحقوق محفوظة © 2021</p>
</div>
</footer>
{/*============= Footer Section Ends Here =============*/}
</div>
)}
}
You need to add render method to your class component
export default class OfficialDocument extends React.Component {
constructor(props) {
super(props);
this.state = {
NCARMap: [],
NCARMapAS: [],
// need to add status
status: 'idle',
};
}
componentDidMount() {
//Get NCARMap data, NCARMapAS used for filtring and sorting the cards
this.setState({
status: 'pending',
});
axios
.get('http://localhost:9200/ncar_index/ncar/_search')
.then((resp) => {
console.log(resp);
this.setState({
NCARMap: resp._source,
NCARMapAS: resp.data,
status: 'success',
});
console.log(this.state.NCARMap);
})
.catch(() => {
this.setState({
status: 'error',
});
});
}
render() {
return (
<div>
{this.state.status === 'pending' && <div>Loading...</div>}
{this.state.status === 'error' && <div>Error</div>}
{this.state.status === 'success' && this.NCARMap.map((item) => {
return <CreateCards key={id} {...item} />;
})}
</div>
);
}
}
I answer this by receives them as objects:
code
<div className="general-card1">
{this.state.noPlaceFound ? (
<h3 className="noPlaceFound">
<i className="fas fa-exclamation-circle fa-sm WarnIcon"></i>
لا يوجد نتائج
</h3>
) : (
this.state.TweetsMap.map((v) => CreateCards(v._source))
)}
</div>

How to open specific post dropdown menu without effecting the others?

I have data that I am looping through and I have a slight issue with a dropdown menu. Whenever I click the dropdown button for a single post all the other posts open. And I don't know to solve it.
Here is the React code
const Post = () {
const [open, setOpen] = useState(false)
return(
{posts.map((post) => {
return (
<div className="card" key={post.postId}>
<div className="card-header">
<div className="card-header__avatar">
<img
src="https://source.unsplash.com/user/erondu/40x40"
alt=""
/>
</div>
<div className="card-header__username">
<span>
<strong>
{post.firstname} {post.lastname}
</strong>
</span>
<br />
<span>
<small>{date}</small>
</span>
</div>
<div
className="card-header__moreBtn"
onClick={() => setOpen(!open)}
>
<img src={More} alt="" />
{open && ( ------> here is where the problem comes
<div class="dropdown-wrapper">
<ul class="dropdown-menu">
<li class="dropdown-menu__item">
<Link href="#d" onClick={deletePost}>Edit</Link>
</li>
<li class="dropdown-menu__item">
<Link className="dropdown-menu__item__link" onClick={deletePost}>Delete</Link>
</li>
</ul>
</div>
)}
</div>
</div>
<div className="postDescription">
<p>{post.postDescription}</p>
</div>
<div className="imgPost">
<img src={post.image} alt="" />
</div>
</div>
)
})}
)
}
Here is a picture
Any help will suffice and I appreciate your time.
You're using the same state value for all items in your loop, so naturally they are going to all follow the same directive.
I would recommend creating a PostItem component that maintains its own state. Something like this:
const PostItem = ({post}) => {
const [open, setOpen] = useState(false)
return (
<div className="card" key={post.postId}>
<div className="card-header">
<div className="card-header__avatar">
<img
src="https://source.unsplash.com/user/erondu/40x40"
alt=""
/>
</div>
<div className="card-header__username">
<span>
<strong>
{post.firstname} {post.lastname}
</strong>
</span>
<br />
<span>
<small>{date}</small>
</span>
</div>
<div
className="card-header__moreBtn"
onClick={() => setOpen(!open)}
>
<img src={More} alt="" />
{open && (
<div class="dropdown-wrapper">
<ul class="dropdown-menu">
<li class="dropdown-menu__item">
<Link href="#d" onClick={deletePost}>Edit</Link>
</li>
<li class="dropdown-menu__item">
<Link className="dropdown-menu__item__link" onClick={deletePost}>Delete</Link>
</li>
</ul>
</div>
)}
</div>
</div>
<div className="postDescription">
<p>{post.postDescription}</p>
</div>
<div className="imgPost">
<img src={post.image} alt="" />
</div>
</div>
)
})
}
const AllPosts = ({posts}) {
return(
{posts.map(post => <PostItem post={post} />
)
}
Now each PostItem has a separate, internal instance of open in its own state and will act independently from the others.

Unable to use div components with bootstrap classes inside map function in react

I have passed the data via props, the console logs show me the data being passed. here is the code below
import React, { Component } from 'react';
import "../../../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./TestimonialCard.css";
const Cards = ({cardData}) =>{
console.log(cardData);
return(
<>
<div className="container">
<div className="row">
<div className="col-md-8 col-center m-auto">
<h2>Testimonials</h2>
<div id="myCarousel" className="carousel slide" data-ride="carousel" >
<div className="carousel-inner">
{cardData.map((slide , index )=>{
{console.log(slide)}
<div className="item carousel-item active" key={index} >
<div className="img-box">
<img src={slide.image} alt={slide.alt}/>
</div>
<p className="testimonial">
{slide.testimonial}
</p>
<p className="overview">
<b> {slide.name} </b> ,<span>{slide.designation}</span>
</p>
</div>
})}
</div>
<a className="carousel-control left carousel-control-prev" href="myCarousel" data-slide="prev">
<i className="fa fa-angle-left"></i>
</a>
<a className="carousel-control right carousel-control-next" href="myCarousel" data-slide="next">
<i className="fa fa-angle-right"></i>
</a>
</div>
</div>
</div>
</div>
</>
)
}
export default Cards
Here, I'm not getting an expected UI under my div with carousel-inner class.
You can use it like this:
import React, { Component } from 'react';
import "../../../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./TestimonialCard.css";
const Cards = ({cardData}) =>{
console.log(cardData);
const cardData = (cardData) => {
cardData.map((slide, index) => {
return (
<div className="item carousel-item active" key={index}>
<div className="img-box">
<img src={slide.image} alt={slide.alt}/>
</div>
<p className="testimonial">
{slide.testimonial}
</p>
<p className="overview">
<b> {slide.name} </b> ,<span>{slide.designation}</span>
</p>
</div>
)
})
}
return(
<>
<div className="container">
<div className="row">
<div className="col-md-8 col-center m-auto">
<h2>Testimonials</h2>
<div id="myCarousel" className="carousel slide" data-ride="carousel" >
<div className="carousel-inner">
{cardData()}
</div>
<a className="carousel-control left carousel-control-prev" href="myCarousel" data-slide="prev">
<i className="fa fa-angle-left"></i>
</a>
<a className="carousel-control right carousel-control-next" href="myCarousel" data-slide="next">
<i className="fa fa-angle-right"></i>
</a>
</div>
</div>
</div>
</div>
</>
)
}
export default Cards
The reason UI was not rendering is because you are using {} instead of () in map inside JSX.
If you want to use map inside render() or the JSX you need to use () instead of {} like this:
{cardData.map((slide , index )=> (
{console.log(slide)}
<div className="item carousel-item active" key={index} >
<div className="img-box">
<img src={slide.image} alt={slide.alt}/>
</div>
<p className="testimonial">
{slide.testimonial}
</p>
<p className="overview">
<b> {slide.name} </b> ,<span>{slide.designation}</span>
</p>
</div>
))}

How do I toggle sidebar on React

I have a toggle example that I have done with Jquery before. Now I want to do it with react, but I don't know how.
I'm putting my Jquery code and React design code below.
React Design Code
Sidebar.js
`
import React from 'react';
import profileImage from '../../../assets/img/profil.jpg';
import iconImage from '../../../assets/img/icon.jpg';
import businessManImage from '../../../assets/img/business-man-white.svg';
import preferencessImage from '../../../assets/img/cogs-white.svg';
import logoutImage from '../../../assets/img/logout.svg';
import toggleImage from '../../../assets/img/toggle-icon.png';
import profileWhite from '../../../assets/img/profile-white.svg';
import classes from '../Sidebar/Sidebar.module.css';
const Sidebar = (props) => {
let url = ""
return (
<div>
<div className={classes['side-bar']}>
<div className={classes['side-bar-top']}>
<div className={classes['side-bar-icon']}>
<img src={iconImage} alt="profileresmi" />
</div>
</div>
<div className={classes['side-bar-row']} style={{height: '100px'}} >
<div className={classes['side-bar-icons']} style={{width: '100px'}} >
<div className={classes['side-bar-profile-image']}>
<img src={profileImage} alt="profileresmi" />
</div>
</div>
<div className={classes['side-bar-profile-content']}>
<h3><b>Mert EKİNCİ</b></h3>
<h4>mert#akturk.de</h4>
</div>
</div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={businessManImage} alt="profileresmi" />
</a>
</div>
<div className={classes['side-bar-text']}>
<a href={url}>Processes</a>
</div>
</div>
<div style={{ clear: 'both' }} ></div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={preferencessImage} alt="profileresmi" />
</a>
</div>
<div className={classes['side-bar-text']}>
<a href={url}>Preferences</a>
</div>
</div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={profileWhite} alt="profileresmi" />
</a>
</div>
<div className={classes['side-bar-text']}>
<a href={url}>User</a>
</div>
</div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={logoutImage} alt="profileresmi" />
</a>
</div>
<div className={classes['side-bar-text']}>
<a href={url}>Logout</a>
</div>
</div>
</div>
<div className={classes['side-toggle']}>
<span className={classes['side-bar-toggle']} >
<img src={toggleImage} alt="profileresmi" />
</span>
</div>
</div>
);
}
export default Sidebar;
`
Here I made the toggle by hiding and showing my divs.
Jquery Sidebar Toggle Code
Script.js
`
var isToggled = true;
var toggleDelay = 50;
var onclickSideToggle = function () {
isToggled = !isToggled;
toggleSidebar(isToggled);
};
$('#side-bar-toggle').on('click', onclickSideToggle);
var toggleSidebar = function (toggle) {
if (toggle) {
$('.side-bar-text').show(toggleDelay);
$('.side-bar-profile-content').show(toggleDelay);
} else {
$(".side-bar-text").hide(toggleDelay);
$('.side-bar-profile-content').hide(toggleDelay);
}
};
`
Can you give me some information on how to do it with React?
If you want just hide/show without any animation you can use the following approach.
More info about usage of useState hook you can find here: https://reactjs.org/docs/hooks-reference.html#usestate
import React, { useState } from 'react';
import profileImage from '../../../assets/img/profil.jpg';
import iconImage from '../../../assets/img/icon.jpg';
import businessManImage from '../../../assets/img/business-man-white.svg';
import preferencessImage from '../../../assets/img/cogs-white.svg';
import logoutImage from '../../../assets/img/logout.svg';
import toggleImage from '../../../assets/img/toggle-icon.png';
import profileWhite from '../../../assets/img/profile-white.svg';
import classes from '../Sidebar/Sidebar.module.css';
const Sidebar = props => {
const [isContentToggled, setIsContentToggled] = useState(true);
let url = ""
return (
<div>
<div className={classes['side-bar']}>
<div className={classes['side-bar-top']}>
<div className={classes['side-bar-icon']}>
<img src={iconImage} alt="profileresmi" />
</div>
</div>
<div className={classes['side-bar-row']} style={{height: '100px'}} >
<div className={classes['side-bar-icons']} style={{width: '100px'}} >
<div className={classes['side-bar-profile-image']}>
<img src={profileImage} alt="profileresmi" />
</div>
</div>
{isContentToggled && (
<div className={classes['side-bar-profile-content']}>
<h3><b>Mert EKİNCİ</b></h3>
<h4>mert#akturk.de</h4>
</div>
)};
</div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={businessManImage} alt="profileresmi" />
</a>
</div>
{isContentToggled && (
<div className={classes['side-bar-text']}>
<a href={url}>Processes</a>
</div>
)}
</div>
<div style={{ clear: 'both' }} ></div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={preferencessImage} alt="profileresmi" />
</a>
</div>
{isContentToggled && (
<div className={classes['side-bar-text']}>
<a href={url}>Preferences</a>
</div>
)}
</div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={profileWhite} alt="profileresmi" />
</a>
</div>
{isContentToggled && (
<div className={classes['side-bar-text']}>
<a href={url}>User</a>
</div>
)}
</div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={logoutImage} alt="profileresmi" />
</a>
</div>
{isContentToggled && (
<div className={classes['side-bar-text']}>
<a href={url}>Logout</a>
</div>
)}
</div>
</div>
<div className={classes['side-toggle']}>
<span onClick={() => setIsContentToggled(prevIsContentToggled => !prevIsContentToggled)} className={classes['side-bar-toggle']}>
<img src={toggleImage} alt="profileresmi" />
</span>
</div>
</div>
);
}
export default Sidebar;
If you want to toggle with the animation code will be almost the same.
You will need just to create some additional className like .hidden with styles for hidden elements and replace
{isContentToggled && (
<div className={classes['side-bar-profile-content']}>
<h3><b>Mert EKİNCİ</b></h3>
<h4>mert#akturk.de</h4>
</div>
)};
with adding/removing this className depending on the isContentToggled value.

Resources