In react js this.state getting state of null in function - reactjs

I want to change backgroundColor on hover but getting error when onMouseOver function get call it says "Uncaught TypeError: Cannot read property 'setState' of null" in console. Please let me know what is wrong with this code thanks.
import React from 'react'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
import Helmet from 'react-helmet'
import { config } from 'config'
export default class Index extends React.Component {
constructor(props) {
super(props);
this.state = {
header: "harry header",
content: "content for harry",
activeClass : 'normal',
hovered :false
}
}
componentDidMount(){
var cssClass = 'normal';
window.addEventListener('scroll', (event) => {
if(event.srcElement.body.scrollTop == 0){
cssClass = 'normal';
}else{
cssClass = 'fixed';
}
this.setState({
activeClass: cssClass,
})
});
}
style() {
if (this.state.hovered) {
return { backgroundColor: "red" }
} else {
return { backgroundColor: "grey" }
}
}
onMouseOver (){
this.setState({ hovered:true });
}
onMouseOut (){
this.setState({ hovered:false });
}
render() {
return (
<div>
<header className={`header ${this.state.activeClass}`} >
<div className="top-bar">
<span>678-827-2782 </span>
<span> hellohello#knotel.com</span>
<button>Login</button>
</div>
</header>
<div className="banner-main-outer">
<div className="banner-main">
</div>
<div className="abs-height-caption">
<div className="caption-banner">
<div className="logo-main"><img src={require('../img/knotel.svg')}/></div>
<h2>Commit to your business, not a lease</h2>
<span>Headquarters as a Service</span>
<button>Book a tour</button>
</div>
<ul className="kno-ul">
<li><a> LOCATIONS</a></li>
<li><a> SPACES</a></li>
<li><a> Services</a></li>
<li><a> Events</a></li>
<li className="kno-hiring"><a> We're hiring</a></li>
</ul>
</div>
<div className="banner-btm-link">
<a>Tenant Reps</a>
<a>I have space</a>
</div>
</div>
<div className="Spaces-Offer">
<div className="header-bar">Our Locations</div>
<div className="map-outer">
<img src={require('../img/map.jpg')} />
</div>
</div>
<div className="our-offer">
<div className="header-bar">Spaces We Offer</div>
<div onMouseOver={this.onMouseOver}
onMouseOut={this.onMouseOut}
style={this.style()} className="offer-cards">
<ul>
<li className="blue-block">
<h1>Flexible Workspace For Growing Teams</h1>
<p>We provide the resources so growing teams can focus their business. Many of our companies have graduated from coworking spaces.</p>
<div className="offer-res-img" />
</li>
<li className="brown-block">
<h1>Branded Floors for Established Companies</h1>
<p>When you need your own floor we provide dedicated, branded space for your company with a backbone of Knotel management.</p>
<div className="offer-res-img" />
</li>
<li className="purple-block">
<h1>Flagship Buildings for World Leaders</h1>
<p>When you are ready to take over the world, Knotel will take over a building for you. Turnkey commercial real estate at any size.</p>
<div className="offer-res-img" />
</li>
</ul>
</div>
</div>
<div className="our-services">
<div className="header-bar">Services We Provide</div>
<div className="sources-cards">
<ul>
<li className="active">
<h1>Sourcing and Buildout</h1>
<p>Knotel bundles property market insight with interior design expertise and buildout management, which ensures the client’s space vision is met on time, on budget, and without headaches.</p>
<div className="sources-res-img" />
</li>
<li>
<h1>Seamless Operations</h1>
<p>Knotel provides comprehensive office services powered by domain experts and best of breed technology. Enjoy the highest ratio of conference rooms per person in the industry, and exclusive deals at a high quality set of partners</p>
<div className="sources-res-img" />
</li>
<li>
<h1>Flexible Terms</h1>
<p>Knotel has a simple pricing structure with flexible terms. We offer various month to month and fixed term agreements tailored to your needs.</p>
<div className="sources-res-img" />
</li>
<li>
<h1>Events and Community</h1>
<p>Knotels are vibrant spaces, with engaged communities and a strong roster of events. Enjoy office hours and informal access to like-minded industry professionals.</p>
<div className="sources-res-img" />
</li>
</ul>
<div className="source-img-change" />
</div>
</div>
<div className="our-events">
<div className="header-bar">Events we're hosting</div>
<div className="form-contact">
<div className="main-outer-inp">
<h1>Stay in the know about Knotel events and news</h1>
<div className="input-blocks">
<input placeholder="First Name (required)" type="text" />
</div>
<div className="input-blocks">
<input placeholder="Last Name (required)" type="text" />
</div>
<div className="input-blocks">
<input placeholder="Email (required)" type="text" />
</div>
</div>
<div className="sub-btn">
<button>SUBSCRIBE</button>
</div>
</div>
</div>
<div className="structure-events">
<div className="structure-container">
<div className="events-details">
<div className="events-knotels">COMING EVENTS</div>
<ul>
<li>
<div className="img-block"><img src={require('../img/manhattan-logo.jpg')} /></div>
<div className="eventdetail">
<div className="dates-on">
<span>07</span>
<p>Jun</p>
</div>
<div className="gtm-para">
<span>Entrepreneurship Council</span>
<p>8:30 am to 10:00 am at Knotel </p>
</div>
</div>
</li>
<li>
<div className="img-block"><img src={require('../img/Parrot Memento Knotel.png')} /></div>
<div className="eventdetail">
<div className="dates-on">
<span>14</span>
<p>Feb</p>
</div>
<div className="gtm-para">
<span>Knotel Private Founders Series</span>
<p>5:00 pm to 7:00 pm at Knotel Union Sq 1</p>
</div>
</div>
</li>
</ul>
</div>
<div className="events-details">
<div className="events-knotels">PAST EVENTS</div>
<ul>
<li>
<div className="img-block"><img src={require('../img/DLD2.jpg')} /></div>
<div className="eventdetail">
<div className="dates-on">
<span>12</span>
<p>May</p>
</div>
<div className="gtm-para">
<span>Future Of Cities - DLD NYC</span>
<p>8:00 am to 2:00 pm at Knotel Bryant </p>
</div>
</div>
</li>
<li>
<div className="img-block"><img src={require('../img/health.jpg')} /></div>
<div className="eventdetail">
<div className="dates-on">
<span>25</span>
<p>Apr</p>
</div>
<div className="gtm-para">
<span>Health Tech Founders' Stories</span>
<p>6:30 pm to 8:30 pm at Knotel Bryant</p>
</div>
</div>
</li>
<li>
<div className="img-block"><img src={require('../img/Space.jpg')} /></div>
<div className="eventdetail">
<div className="dates-on">
<span>20</span>
<p>Apr</p>
</div>
<div className="gtm-para">
<span>When Do We Go To Space?</span>
<p>6:30 pm to 8:30 pm at Knotel Bryant</p>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
<footer>
<div className="footer">
<div className="img-footer">
<img src={require('../img/knotel.svg')} />
</div>
<ul>
<li><a>Careers</a></li>
<li><a>Terms</a></li>
<li><a>Tenant Reps</a></li>
<li><a>I have space</a></li>
</ul>
<div className="Copyright-res">Copyright © 2017 KNOTEL. All rights reserved.</div>
</div>
</footer>
</div>
)
}
}

From the docs:
You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.
This is not React-specific behavior; it is a part of how functions work in JavaScript.
So you need to bind this to your methods to in order to make it work.
This is how your constructor should look:
constructor(props) {
super(props);
this.state = {
header: "harry header",
content: "content for harry",
activeClass: "normal",
hovered: false
}
this.onMouseOver = this.onMouseOver.bind(this)
this.onMouseOut = this.onMouseOut.bind(this)
}

You need to bind you class methods to this instance. One way to do that is in the constructor -
constructor(props) {
super(props);
this.onMouseOver = this.onMouseOver.bind(this)
this.onMouseOut = this.onMouseOut.bind(this)
this.state = {
header: "harry header",
content: "content for harry",
activeClass : 'normal',
hovered :false
}
}
Whenever you get an error which you can trace back to cannot read property x of null where null was supposed to be this, you know that the binding for this is not correct at the time the method/function was called.

The other answers are correct, but you can also add the events to the higher order <div>
so you can modify your component to be like
return (
<div onMouseOut={this.onMouseOut} onMouseOver={this.onMouseOver}>
...
</div>
);

Related

Browser URL updates but components do not update

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!

Problems with the UseState hook typing

I'm trying to put useState hook values to a component via props.
As I understand typescript complains that I didn't specify setActive to boolean type. Am I right? If so, how can I do it?
const Card = () => {
const [activeModal, setActiveModal] = useState<boolean>(false)
return (
<>
<ApproveModal active={activeModal} setActive={setActiveModal} />
<div className="card">
<div className="card-wrapper">
<div className="card-header">
<div className="card-header-left">
<img src={token} alt="token" />
<div className="card-header-info-tag">
<h1>WETH-WBNB LP</h1>
<p>Auto-Compounding</p>
</div>
</div>
<div className="card-header-right">
<p>Pancake</p>
<img src={pancake} alt="pancake" />
</div>
</div>
<div className="card-info">
<div className="card-info-item">
<div className="card-info-item-title">Staked</div>
<div className="card-info-item-value">$482.22K</div>
<div className="card-info-item-description">39595 LPs</div>
</div>
<div className="card-info-item">
<div className="card-info-item-title">APY</div>
<div className="card-info-item-value">365%</div>
<div className="card-info-item-description">Daily: 2.00%</div>
</div>
<div className="card-info-item">
<div className="card-info-item-title">TVL</div>
<div className="card-info-item-value">$482.22K</div>
<div className="card-info-item-description">39595 LPs</div>
</div>
</div>
<div className="card-button" onClick={() => setActiveModal(!activeModal)}>Approve</div>
</div>
</div>
</>
)
}
"text to fix little text problem"
"text to fix little text problem"
"text to fix little text problem"
And ApproveModal
interface ApproveModalProps {
active: boolean;
setActive: boolean;
}
const ApproveModal = ({active, setActive}: ApproveModalProps) => {
return (
<div className="modal">
<div className="modal-content">
<div className="modal-header">
<img src={modalLogo} alt="modalLogo" />
<div className="modal-header-info">
<div className="modal-header-info-title">WETH-WBNB LP</div>
<div className="modal-header-info-description">Auto-Compounding</div>
</div>
<div className="modal-header-info-swap">#PancakeSwap</div>
<img src={closeIcon} alt="closeIcon" className="close-button" />
</div>
<div className="modal-actions">
<div className="modal-actions-buttons">
<div className="deposit">Deposit</div>
<div className="withdrow">Withdrow</div>
</div>
</div>
<div className="modal-balance">
<div className="modal-balance-header">
<div className="modal-balance-header-left">
<div className="balance">Balance</div>
<div className="link">Create LP</div>
</div>
<div className="modal-balance-header-right">
<img src={updateIcon} alt="updateIcon" />
<div className="value">0.0000</div>
<div className="value-description">($0.00)</div>
</div>
</div>
<div className="balance-input">
<input type="text" />
<div className="input-button">MAX</div>
</div>
</div>
<div className="modal-info">
<div className="modal-info-apy">
<div className="modal-info-apy-title">APY</div>
<div className="modal-info-item">
<div className="apy-value">365%</div>
<div className="apr-value">APR: Swap 70.9% + GROW 73.5%</div>
</div>
</div>
<div className="modal-info-contact">
<div className="modal-info-contact-title">Contact</div>
<div className="modal-info-item">
<div className="contact-link">View on BScScan</div>
<div className="contact-address">oxAD6bD158869a97219447cf63b090</div>
</div>
</div>
<div className="modal-button">Approve</div>
<h1>No deposit free. No withdraw free.</h1>
</div>
</div>
</div>
)
}
Here is the code
The problem lies in your Card component. The error is saying that the setActive prop expects to receive a boolean value, but you are providing it with a function.
It should be expecting a function. You’ll want to change the props types on your Card such that setActive is a function whose argument is a boolean.
interface CardProps {
setActive: (active: boolean) => void;
…
If you want to be able to use a prevState callback when calling setActive inside the Card component, then you can use the exact type of your setActiveModal function, which is this:
interface CardProps {
setActive: React.Dispatch<React.SetStateAction<boolean>>;
…

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 view detail of a certain Item in reactjs and laravel application [duplicate]

This question already has answers here:
Render is called twice when fetching data from a REST API
(3 answers)
Closed 2 years ago.
I try to get my pe list details on my single page when I click on the view details button but facing some issue so please help.
when i do {JSON.stringify(pet)} it gives a list of data proper but when I try to bind it's not showing any data but I check a network it gives proper data
my description.js component
import React, {useState, useEffect} from "react";
import {Link} from 'react-router-dom';
import Form from "./Form";
import Related from "./Related";
import WhySafari from "./WhySafari";
import {read} from "./apiCore";
const Description = (props) => {
const [pet, setPet] = useState({});
const [error, setError] = useState(false);
const loadsingelPet = id => {
read(id).then(data =>{
if(data.error){
setError(data.error);
}else{
setPet(data);
}
});
};
useEffect(() =>{
const id = props.match.params.id;
loadsingelPet(id);
}, [])
return(
<div>
<div className="bradcam_area breadcam_bg">
<div className="container">
<div className="row">
<div className="col-lg-12">
<div className="bradcam_text text-center">
<h3>{pet && pet.pbrd_display_name}</h3>
<ul>
<li><Link to="/">Home</Link> <i className="ti-angle-right"></i> </li>
<li><Link to="/list">Puppies for sale</Link> <i className="ti-angle-right"></i> </li>
<li><Link to="#">Golden Doodle</Link><i className="ti-angle-right"></i></li>
<li><Link to="#">German Shepherd</Link></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<section className="sample-text-area">
<div className="container">
<div className="row">
{/* {JSON.stringify(pet)} */}
<div className="col-lg-6">
<div className="gallery-container">
<div className="swiper-container gallery-main">
<div className="swiper-wrapper">
<div className="swiper-slide">
<Link to="img/puppy/1.png" data-fancybox="group1">
<img src={"http://localhost:8000/storage/uploads/puppies/"+pet.pet_image_ids} alt={pet.pet_image_ids}/>
</Link>
</div>
</div>
</div>
<div className="left-thumb">
<div className="swiper-container gallery-thumbs">
<div className="swiper-wrapper">
<div className="swiper-slide">
<img src="img/puppy/1.png" alt="Slide 01" />
</div>
<div className="swiper-slide">
<img src="img/puppy/1.png" alt="Slide 01" />
</div>
<div className="swiper-slide">
<img src="img/puppy/1.png" alt="Slide 01" />
</div>
</div>
</div>
<div className="swiper-button-prev"></div>
<div className="swiper-button-next"></div>
</div>
</div>
</div>
<div className="col-lg-6">
<div className="product-details">
<h1>{pet.pbrd_display_name}</h1>
<ul className="dtails-price">
<li className="real-price">$3449</li>
<li className="old-price">$4469</li>
</ul>
<div className="product-specification">
<h4><strong>Puppy Id : </strong> #656171</h4>
<h4><strong>Gender : </strong> {pet && pet.loc_contact_numbers }</h4>
<h4><strong>DOB : </strong> {pet && pet.plttr_birthdate }</h4>
<h4><strong>Location : </strong> {pet && pet.loc_receipt_name} </h4>
</div>
<div className="call-section">
<div className="call-left">
<img src="img/phone.svg" />
<h4>Need a nuppy guidience? <span>{pet && pet.loc_contact_numbers }</span></h4>
</div>
<div className="call-right">
<Link to="#" className="boxed-btn3">{pet && pet.pstatus_name }</Link>
</div>
</div>
<div className="decription-parra">
<h4>Description :</h4>
<p>{pet && pet.description}</p>
</div>
</div>
</div>
</div>
</div>
</section>
<Form/>
<WhySafari />
<Related />
</div>
);
}
export default Description;
please help. thanks in advance
Try useEffect like this:
useEffect(() =>{
const id = props.match.params.id;
loadsingelPet(id);
}, [props.match.params.id])
So it will re-run the effect if (props.match.params.id) changes and Ui will update too. React Documentation on hooks can be useful: https://reactjs.org/docs/hooks-effect.html

Get bootstrap modal close event in reactjs

I am using React 16 with Bootstrap 4.
I am using bootstrap modal to display some values. I need to reset these values whenever modal is closed.
For Modal I have created a separate component. I dont want to use React-Modal as I get all the functionality in the current modal.
I know in plain javascript it is achieved using below code:
$(".modal").on("hidden.bs.modal"){
//reset values here
};
But I dont know how this is achieved in ReactJS?
Below is my code for modal:
<div className="modal fade modal-flex" id="large-Modal-OneUser" tabIndex={-1} role="dialog">
<div className="modal-dialog modal-lg" role="document">
<div className="modal-content">
<div className="modal-header" style={{display: 'block'}}>
<div className="row">
<div className="col-md-6">
<h2 style={{fontWeight:600}}>{newTimelineData.length > 0 ? newTimelineData[0].candidateName : ""}</h2>
</div>
<div className="col-md-6">
<span style={{display: 'inline-flex',alignItems: 'center',float:'right'}}><h4 style={{paddingRight:20}}>{isNotEmpty(this.state.scheduledFor) ? moment(this.state.scheduledFor).format("DD-MMM-YYYY"):this.checkScheduledFor(newTimelineData)}</h4>
<h3 style={{paddingRight: 10}}>{isNotEmpty(this.state.probability) ? this.getProbabilityHTML() : this.checkProbability(newTimelineData)}</h3>
{/*<button type="button" className="close" data-dismiss="modal" aria-label="Close" style={{marginTop: 0,marginBottom: 10}}>
<span aria-hidden="true">×</span>
</button>*/}
</span>
</div>
</div>
</div>
<div className="modal-body">
<div className="col-md-12">
{/*<div className="card">*/}
{/*<div className="card-block">*/}
{/* Horizontal Timeline start */}
<div className="cd-horizontal-timeline">
<div className="timeline">
<div className="events-wrapper">
<div className="events" id="foo">
<ol>
{newTimelineData.map((item, index) => (
<li key={item.id}>
<a
href="#0" onClick={()=> this.setHeaders(item)}
data-date={moment(item.scheduledFor).format('DD/MM/YYYY')}
className={index === 0 ? 'selected' : null}>
<Moment unix format="DD MMM">
{item.scheduledFor / 1000}
</Moment>
</a>
</li>
))}
</ol>
<span className="filling-line" aria-hidden="true" />
</div>
{/* .events */}
</div>
{/* .events-wrapper */}
<ul className="cd-timeline-navigation">
<li>
<a href="#0" className="prev inactive">
Prev
</a>
</li>
<li>
<a href="#0" className="next">
Next
</a>
</li>
</ul>
{/* .cd-timeline-navigation */}
</div>
{/* .timeline */}
<div className="events-content">
<ol>
{newTimelineData.map((item, index) => (
<li
key={item.id}
className={index === 0 ? 'selected' : null}
data-date={moment(item.scheduledFor).format('DD/MM/YYYY')}>
<div className="row">
<div className="col-sm-8" style={{fontSize:'1rem',paddingLeft: 3,paddingRight:0}}><b>Job</b> : {item.jobName}</div>
{isNotEmpty(joiningDate) && <div className="col-sm-4" style={{fontSize:'1rem',paddingLeft: 3,paddingRight:0}}><b>Joined Date : </b>{joiningDate}</div>}
</div>
<div className="row">
<div className="col-sm-8" style={{fontSize:'1rem',padding:0}}><b>Stage</b> : {this.props.stage}</div>
{isNotEmpty(offerDate) && <div className="col-sm-4" style={{fontSize:'1rem',paddingLeft: 0,paddingRight:0}}><b>Offer Date : </b>{offerDate}</div>}
</div>
<br></br>
<div className="row">
<div className="col-sm-12" style={{fontSize:'1rem',paddingLeft: 0}}><b>Comments</b> :<br></br>{item.comments}</div>
</div>
</li>
))}
</ol>
</div>
{/* .events-content */}
</div>
{/* Horizontal Timeline end */}
{/*</div>*/}
{/*</div>*/}
</div>
</div>
<div className="modal-footer">
<button style={{backgroundColor: '#8080808f',borderColor:'#8080808f'}}
type="button"
className="btn btn-primary waves-effect waves-light"
data-dismiss="modal">
Close
</button>
</div>
</div>
</div>
</div>
Can anyone help?
See below snapshot for the work around I have tried suggested by #Jayavel.
Implemented a small workaround and hope it's fulfills your need, With my understanding you load your modal body with state and user will change something and you store those in the same state.
While closing the modal(close button) you need to reset the initial state i.e reset to default values.
Is that right !!! check this demo
what you need is,
store your default state like below:
const initialState = {
isOpen: false,
value: "defaultvalue"
};
and in component :
class App extends Component {
constructor(props) {
super(props);
this.state = initialState; // stored defaultstate
}
toggleModal = () => {
this.setState({
isOpen: !this.state.isOpen
});
}
toggleModalClose = () => { // modal close to reset input val
this.setState(initialState);
}
handleChange = (e) => {
this.setState({
value: e.target.value //input new value
});
}
render() {
return (
<div className="App">
<button onClick={this.toggleModal}>
Open the modal
</button>
<Modal show={this.state.isOpen}
onClose={this.toggleModalClose}>
<input type="text" value={this.state.value} onChange={this.handleChange} />
</Modal>
</div>
);
}
}
Hope this helps.

Resources