How can I use a trigger event to a menu item in Bulma dropdown in react?
I don't know how to hide the menu since the button is not the parent of the menu.
<div className="dropdown is-active">
<div className="dropdown-trigger">
<button className="button" aria-haspopup="true" aria-controls="dropdown-menu">
<span>Dropdown button</span>
<span className="icon is-small">
<i className="fas fa-angle-down" aria-hidden="true"></i>
</span>
</button>
</div>
<div className="dropdown-menu" id="dropdown-menu" role="menu">
<div className="dropdown-content">
<a href="#" class="dropdown-item">
Dropdown item
</a>
</div>
</div>
</div>
This can be done by toggling class name based on a condition. Here is an example based on your code:
class App extends React.Component {
constructor(props) {
super(props);
this.state = { collapsed: true };
}
handleToggle() {
this.setState({ collapsed: !this.state.collapsed });
}
render() {
return(
<div className={"dropdown" + (this.state.collapsed ? "" : " is-active")} tabIndex="0" onBlur={() => this.handleToggle()}>
<div className="dropdown-trigger">
<button className="button" aria-haspopup="true" aria-controls="dropdown-menu" onClick={() => this.handleToggle()}>
<span>Dropdown button</span>
<span className="icon is-small">
<i className="fas fa-angle-down" aria-hidden="true"></i>
</span>
</button>
</div>
<div className="dropdown-menu" id="dropdown-menu" role="menu">
<div className="dropdown-content">
Dropdown item
</div>
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.8.0/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<div id="root"></div>
This is my answer.
is-hidden is bulma's function
state = {
isHide: "is-hidden"
}
handleToggle = () => {
if(this.state.isHide == "is-hidden") {
this.setState(state => ({
isHide: ""
}));
}
else {
this.setState(state => ({
isHide: "is-hidden"
}));
}
}
<div className="dropdown is-active">
<div className="dropdown-trigger">
<button className="button" aria-haspopup="true" aria-controls="dropdown-menu">
<span>Dropdown button</span>
<span className="icon is-small">
<i className="fas fa-angle-down" aria-hidden="true"></i>
</span>
</button>
</div>
<div className={menuHidden} id="dropdown-menu" role="menu">
<div className="dropdown-content">
<a href="#" class="dropdown-item">
Dropdown item
</a>
</div>
</div>
</div>
Related
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>
I'm new to react.js. in my code, I would like to pass these menu items such as dashboard, Customer,.. as props, and I would like to use a map on it. I want to use the map function that will return JSX. How can I do this? I did not know how to loop through props and render a list of items. also how I can use the default props for them?
import './Sidebar.css';
import React, { Component } from 'react';
class Sidebar extends Component {
constructor(props) {
super(props);
this.state = { }
}
render() {
return (
<div className="wrapper d-flex align-items-stretch">
<nav id="sidebar">
<div className="custom-menu">
<button type="button" id="sidebarCollapse" className="btn btn-primary">
<i className="fa fa-bars"></i>
<span className="sr-only">Toggle Menu</span>
</button>
</div>
<div className="p-4">
<h1>Donyaro </h1>
<ul className="list-unstyled components mb-5">
<li className="active">
</i> Dashboard
</li>
<li>
</i> Customer
</li>
<li>
</i> Category
</li>
<li>
</i> Transaction
</li>
<li>
</i> Pick-up
</li>
<li>
</i> Stock
</li>
<li>
</i> Financial
</li>
<li>
</i> Report
</li>
</ul>
</div>
<div class="footer">
</i>
<h6><span>Welcome, </span>Add Business
</h6>
</div>
</nav>
</div>
);
}
}
export default Sidebar;
Create the desired array and map through it like this:
import './Sidebar.css';
import React, { Component } from 'react';
class Sidebar extends Component {
constructor(props) {
super(props);
this.state = {
menuItems: ['Dashboard','Customer','Category','Transaction','Pick-up','Stock','Finnancial','Report']
}
}
render() {
return (
<div className="wrapper d-flex align-items-stretch">
<nav id="sidebar">
<div className="custom-menu">
<button type="button" id="sidebarCollapse" className="btn btn-primary">
<i className="fa fa-bars"></i>
<span className="sr-only">Toggle Menu</span>
</button>
</div>
<div className="p-4">
<h1>Donyaro </h1>
<ul className="list-unstyled components mb-5">
{this.state.menuItems.map(item=> {return
<li className="active">
</i>{item}
</li>
})
}
</ul>
</div>
<div class="footer">
</i>
<h6><span>Welcome, </span>Add Business
</h6>
</div>
</nav>
</div>
);
}
}
export default Sidebar;
We are building an e-commerce project using react-redux as a front-end language. Hence we have to display product categories in our application. So we use the Axios library to access JSON data from the server. Everything is working fine but when I console log response data then I get the undefined message.
Please help me to solve this problem...
category component:
import React, { Component } from "react";
import Slider from "react-slick";
import Breadcrumb from "../../common/breadcrumb";
import { Slider6, Slider4 } from "../../../services/script";
import "react-tabs/style/react-tabs.scss";
import { connect } from "react-redux";
class ElementCategory extends Component {
render() {
console.log(this.props.categories);
return (
<div>
<Breadcrumb parent={"Elements"} title={"Category"} />
{/*Category One*/}
<div className="container">
<section className="section-b-space">
<div className="row">
<div className="col">
<Slider {...Slider6} className="slide-6 no-arrow">
<div className="category-block">
<a href="#">
<div className="category-image">
<img
src={`${process.env.PUBLIC_URL}/assets/images/icon/cat1.png`}
alt=""
/>
</div>
</a>
<div className="category-details">
<a href="#">
<h5>sport shoes</h5>
</a>
</div>
</div>
<div className="category-block">
<a href="#">
<div className="category-image">
<img
src={`${process.env.PUBLIC_URL}/assets/images/icon/cat2.png`}
alt=""
/>
</div>
</a>
<div className="category-details">
<a href="#">
<h5>casual shoes</h5>
</a>
</div>
</div>
<div className="category-block">
<a href="#">
<div className="category-image">
<img
src={`${process.env.PUBLIC_URL}/assets/images/icon/cat3.png`}
alt=""
/>
</div>
</a>
<div className="category-details">
<a href="#">
<h5>formal shoes</h5>
</a>
</div>
</div>
<div className="category-block">
<a href="#">
<div className="category-image">
<img
src={`${process.env.PUBLIC_URL}/assets/images/icon/cat4.png`}
alt=""
/>
</div>
</a>
<div className="category-details">
<a href="#">
<h5>flat</h5>
</a>
</div>
</div>
<div className="category-block">
<a href="#">
<div className="category-image">
<img
src={`${process.env.PUBLIC_URL}/assets/images/icon/cat5.png`}
alt=""
/>
</div>
</a>
<div className="category-details">
<a href="#">
<h5>heels</h5>
</a>
</div>
</div>
<div className="category-block">
<a href="#">
<div className="category-image">
<img
src={`${process.env.PUBLIC_URL}/assets/images/icon/cat6.png`}
alt=""
/>
</div>
</a>
<div className="category-details">
<a href="#">
<h5>boots</h5>
</a>
</div>
</div>
<div className="category-block">
<a href="#">
<div className="category-image">
<img
src={`${process.env.PUBLIC_URL}/assets/images/icon/cat2.png`}
alt=""
/>
</div>
</a>
<div className="category-details">
<a href="#">
<h5>casual shoes</h5>
</a>
</div>
</div>
<div className="category-block">
<a href="#">
<div className="category-image">
<img
src={`${process.env.PUBLIC_URL}/assets/images/icon/cat3.png`}
alt=""
/>
</div>
</a>
<div className="category-details">
<a href="#">
<h5>casual shoes</h5>
</a>
</div>
</div>
</Slider>
</div>
</div>
</section>
</div>
{/*Category Two*/}
<section className="p-0 ratio2_1">
<div className="container-fluid">
<div className="row category-border">
<div className="col-sm-4 border-padding">
<div className="category-banner">
<div>
<img
src={`${process.env.PUBLIC_URL}/assets/images/cat1.png`}
className="img-fluid blur-up lazyload bg-img"
alt=""
/>
</div>
<div className="category-box">
<a href="#">
<h2>men</h2>
</a>
</div>
</div>
</div>
<div className="col-sm-4 border-padding">
<div className="category-banner">
<div>
<img
src={`${process.env.PUBLIC_URL}/assets/images/cat2.png`}
className="img-fluid blur-up lazyload bg-img"
alt=""
/>
</div>
<div className="category-box">
<a href="#">
<h2>women</h2>
</a>
</div>
</div>
</div>
<div className="col-sm-4 border-padding">
<div className="category-banner">
<div>
<img
src={`${process.env.PUBLIC_URL}/assets/images/cat3.png`}
className="img-fluid blur-up lazyload bg-img"
alt=""
/>
</div>
<div className="category-box">
<a href="#">
<h2>kids</h2>
</a>
</div>
</div>
</div>
</div>
</div>
</section>
{/*Category Three*/}
<div className="container category-button">
<section className="section-b-space">
<div className="row partition1">
<div className="col">
<a href="#" className="btn btn-outline btn-block">
airbag
</a>
</div>
<div className="col">
<a href="#" className="btn btn-outline btn-block">
burn bag
</a>
</div>
<div className="col">
<a href="#" className="btn btn-outline btn-block">
briefcase
</a>
</div>
<div className="col">
<a href="#" className="btn btn-outline btn-block">
carpet bag
</a>
</div>
<div className="col">
<a href="#" className="btn btn-outline btn-block">
money bag
</a>
</div>
<div className="col">
<a href="#" className="btn btn-outline btn-block">
tucker bag
</a>
</div>
</div>
</section>
</div>
{/*Category Four*/}
<div className="category-bg ratio_square">
<div className="container-fluid p-0">
<div className="row order-section">
<div className="col-sm-4 p-0">
<a href="#" className="image-block">
<img
alt=""
src={`${process.env.PUBLIC_URL}/assets/images/cat1.jpg`}
className="img-fluid blur-up lazyload bg-img"
/>
</a>
</div>
<div className="col-sm-4 p-0">
<div className="contain-block even">
<div>
<h6>new products</h6>
<a href="#">
<h2>zipper storage bag</h2>
</a>
<a href="#" className="btn btn-solid category-btn">
-80% off
</a>
<a href="#">
<h6>
<span>shop now</span>
</h6>
</a>
</div>
</div>
</div>
<div className="col-sm-4 p-0">
<a href="#" className="image-block">
<img
alt=""
src={`${process.env.PUBLIC_URL}/assets/images/cat2.jpg`}
className="img-fluid blur-up lazyload bg-img"
/>
</a>
</div>
<div className="col-sm-4 p-0">
<div className="contain-block">
<div>
<h6>on sale</h6>
<a href="#">
<h2>tucker bag</h2>
</a>{" "}
<a href="#" className="btn btn-solid category-btn">
save 30% off
</a>
<a href="#">
<h6>
<span>shop now</span>
</h6>
</a>
</div>
</div>
</div>
<div className="col-sm-4 p-0">
<a href="#" className="image-block even">
<img
alt=""
src={`${process.env.PUBLIC_URL}/assets/images/cat3.jpg`}
className="img-fluid blur-up lazyload bg-img"
/>
</a>
</div>
<div className="col-sm-4 p-0">
<div className="contain-block">
<div>
<h6>summer sale</h6>
<a href="#">
<h2>gate check bag</h2>
</a>{" "}
<a href="#" className="btn btn-solid category-btn">
minimum 50% off
</a>
<a href="#">
<h6>
<span>shop now</span>
</h6>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
{/*Category Five*/}
<section className="ratio_portrait">
<div className="container">
<div className="row">
<div className="col">
<Slider {...Slider4} className="slide-4 category-m no-arrow">
<div>
<div className="category-wrapper">
<div>
<div>
<img
src={`${process.env.PUBLIC_URL}/assets/images/watch/cat1.png`}
className="img-fluid blur-up lazyload bg-img"
alt=""
/>
</div>
<h4>watch models</h4>
<ul className="category-link">
<li>
d1 milano
</li>
<li>
damaskeening
</li>
<li>
diving watch
</li>
<li>
dollar watch
</li>
</ul>
<a href="#" className="btn btn-outline">
view more
</a>
</div>
</div>
</div>
<div>
<div className="category-wrapper">
<div>
<div>
<img
src={`${process.env.PUBLIC_URL}/assets/images/watch/cat2.png`}
className="img-fluid blur-up lazyload bg-img"
alt=""
/>
</div>
<h4>calculator watch</h4>
<ul className="category-link">
<li>
Shock-resistant watch
</li>
<li>
Skeleton watch
</li>
<li>
Slow watch
</li>
<li>
Solar-powered watch
</li>
</ul>
<a href="#" className="btn btn-outline">
view more
</a>
</div>
</div>
</div>
<div className="category-wrapper">
<div>
<div>
<img
src={`${process.env.PUBLIC_URL}/assets/images/watch/cat3.png`}
className="img-fluid blur-up lazyload bg-img"
alt=""
/>
</div>
<h4>Antimagnetic watch</h4>
<ul className="category-link">
<li>
Watchmaking conglomerates
</li>
<li>
Breitling SA
</li>
<li>
Casio watches
</li>
<li>
Citizen Watch
</li>
</ul>
<a href="#" className="btn btn-outline">
view more
</a>
</div>
</div>
<div className="category-wrapper">
<div>
<div>
<img
src={`${process.env.PUBLIC_URL}/assets/images/watch/cat2.png`}
className="img-fluid blur-up lazyload bg-img"
alt=""
/>
</div>
<h4>History of watches</h4>
<ul className="category-link">
<li>
Manufacture d'horlogerie
</li>
<li>
Mechanical watch
</li>
<li>
Microbrand watches
</li>
<li>
MIL-W-46374
</li>
</ul>
<a href="#" className="btn btn-outline">
view more
</a>
</div>
</div>
<div className="category-wrapper">
<div>
<div>
<img
src={`${process.env.PUBLIC_URL}/assets/images/watch/cat1.png`}
className="img-fluid blur-up lazyload bg-img"
alt=""
/>
</div>
<h4>watch models</h4>
<ul className="category-link">
<li>
d1 milano
</li>
<li>
damaskeening
</li>
<li>
diving watch
</li>
<li>
dollar watch
</li>
</ul>
<a href="#" className="btn btn-outline">
view more
</a>
</div>
</div>
</Slider>
</div>
</div>
</div>
</section>
{/*Category Six*/}
<section className="section-b-space">
<div className="container">
<div className="row background">
<div className="col">
<a href="#">
<div className="contain-bg">
<h4 data-hover="size 06">size 06</h4>
</div>
</a>
</div>
<div className="col">
<a href="#">
<div className="contain-bg">
<h4>size 07</h4>
</div>
</a>
</div>
<div className="col">
<a href="#">
<div className="contain-bg">
<h4>size 08</h4>
</div>
</a>
</div>
<div className="col">
<a href="#">
<div className="contain-bg">
<h4>size 09</h4>
</div>
</a>
</div>
<div className="col">
<a href="#">
<div className="contain-bg">
<h4>size 10</h4>
</div>
</a>
</div>
</div>
</div>
</section>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
categories: state.category,
};
};
export default connect(mapStateToProps, null)(ElementCategory);
shop.js:
/**
* Mocking client-server processing
*/
import axios from "axios";
// import _products from './data.json'
import React, { useState, useEffect } from "react";
import store from "../store";
import { receiveProducts } from "../actions/index";
const TIMEOUT = 100;
const _products = axios
.get(`http://localhost:4000/product`)
.then((response) => {
return response.data;
});
const _category = axios
.get(`http://localhost:4000/categories`)
.then((response) => {
return response.data;
});
export default {
getProducts: (cb, timeout) =>
setTimeout(() => cb(_products), timeout || TIMEOUT),
getCategories: (cb, timeout) =>
setTimeout(() => cb(_category), timeout || TIMEOUT),
buyProducts: (payload, cb, timeout) =>
setTimeout(() => cb(), timeout || TIMEOUT),
};
action/index.js:
import shop from "../api/shop";
import * as types from "../constants/ActionTypes";
import store from "../store";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.min.css";
export const fetchProductsBegin = () => ({
type: types.FETCH_PRODUCTS_BEGIN,
});
export const receiveProducts = (products) => ({
type: types.RECEIVE_PRODUCTS,
products,
});
export const fetchCategoriesBegin = () => ({
type: types.FETCH_CATEGORIES_BEGIN,
});
export const receiveCategories = (categories) => ({
type: types.RECEIVE_CATEGORIES,
categories,
});
export const getAllProducts = () => (dispatch) => {
dispatch(fetchProductsBegin());
return shop.getProducts((products) => {
products.then((data) => {
dispatch(receiveProducts(data));
});
});
};
export const getAllCategories = () => (dispatch) => {
dispatch(fetchCategoriesBegin());
return shop.getCategories((categories) => {
categories.then((data) => {
dispatch(receiveCategories(data));
});
});
};
export const fetchSingleProduct = (productId) => ({
type: types.FETCH_SINGLE_PRODUCT,
productId,
});
export const fetchSingleCategory = (categoryId) => ({
type: types.FETCH_SINGLE_PRODUCT,
categoryId,
});
//it seems that I should probably use this as the basis for "Cart"
export const addToCart = (product, qty) => (dispatch) => {
toast.success("Item Added to Cart");
dispatch(addToCartUnsafe(product, qty));
};
export const addToCartAndRemoveWishlist = (product, qty) => (dispatch) => {
toast.success("Item Added to Cart");
dispatch(addToCartUnsafe(product, qty));
dispatch(removeFromWishlist(product));
};
export const addToCartUnsafe = (product, qty) => ({
type: types.ADD_TO_CART,
product,
qty,
});
export const removeFromCart = (product_id) => (dispatch) => {
toast.error("Item Removed from Cart");
dispatch({
type: types.REMOVE_FROM_CART,
product_id,
});
};
export const incrementQty = (product, qty) => (dispatch) => {
toast.success("Item Added to Cart");
dispatch(addToCartUnsafe(product, qty));
};
export const decrementQty = (productId) => (dispatch) => {
toast.warn("Item Decrement Qty to Cart");
dispatch({
type: types.DECREMENT_QTY,
productId,
});
};
//it seems that I should probably use this as the basis for "Wishlist"
export const addToWishlist = (product) => (dispatch) => {
toast.success("Item Added to Wishlist");
dispatch(addToWishlistUnsafe(product));
};
export const addToWishlistUnsafe = (product) => ({
type: types.ADD_TO_WISHLIST,
product,
});
export const removeFromWishlist = (product_id) => (dispatch) => {
toast.error("Item Removed from Wishlist");
dispatch({
type: types.REMOVE_FROM_WISHLIST,
product_id,
});
};
//Compare Products
export const addToCompare = (product) => (dispatch) => {
toast.success("Item Added to Compare");
dispatch(addToCompareUnsafe(product));
};
export const addToCompareUnsafe = (product) => ({
type: types.ADD_TO_COMPARE,
product,
});
export const removeFromCompare = (product_id) => ({
type: types.REMOVE_FROM_COMPARE,
product_id,
});
// Filters
export const filterBrand = (brand) => ({
type: types.FILTER_BRAND,
brand,
});
export const filterColor = (color) => ({
type: types.FILTER_COLOR,
color,
});
export const filterPrice = (value) => ({
type: types.FILTER_PRICE,
value,
});
export const filterSort = (sort_by) => ({
type: types.SORT_BY,
sort_by,
});
// Currency
export const changeCurrency = (symbol) => ({
type: types.CHANGE_CURRENCY,
symbol,
});
reducer/categories.js:
import { RECEIVE_CATEGORIES } from "../constants/ActionTypes";
const initialState = {
category: [],
};
const categoryReducer = (state = initialState, action) => {
switch (action.type) {
case RECEIVE_CATEGORIES:
return { ...state, categories: action.categories };
default:
return state;
}
};
export default categoryReducer;
reducer/index.js:
import { combineReducers } from "redux";
import { IntlReducer as Intl, IntlProvider } from "react-redux-multilingual";
// Import custom components
import productReducer from "./products";
import categories from "./categories";
import cartReducer from "./cart";
import filtersReducer from "./filters";
import wishlistReducer from "./wishlist";
import compareReducer from "./compare";
const rootReducer = combineReducers({
data: productReducer,
categories,
cartList: cartReducer,
filters: filtersReducer,
wishlist: wishlistReducer,
compare: compareReducer,
Intl,
});
export default rootReducer;
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.
can you help me understand why this onClick event does not bind to the button and won't fire?
class DateSlider extends React.Component{
constructor(props){
super(props);
this.state = {
allValues: this.props.allValues,
}
this.onClick = this.onClick.bind(this);
}
onClick(){
console.log('here');
// this.props.change(event.target.text);
}
render(){
return (
<div class="date-slider col-xl-4 col-12">
<div class="row">
<div class="date-input-description col-xl-12 col-12">{this.props.unit}</div>
<div class="col-xl-12 date-picker-container">
<div class="col-xl-12">
<div class="row" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<div class="date-range col-xl-9 col-9">{this.props.initialValue}</div>
<div class="col-xl-3 col-9 date-picker-small-button">
<img class="mx-auto d-block" src="./images/small-arrow-down.svg" />
</div>
<div class="dropdown-menu dropdown-menu-right">
{
//HERE
this.state.allValues.map((value) => {
return <button key={value} class="dropdown-item" type="button" onClick={this.onClick}>{value}</button>
})
}
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
When clicking on the item that is rendered, it won't console.log anything.
this.state.allValues.map((value) => {
return <button key={value} class="dropdown-item" type="button" onClick={this.onClick}>{value}</button>})
should be
this.state.allValues.map((value) => {
return <button key={value} className="dropdown-item" type="button" onClick={this.onClick}>{value}</button>})
In other words: replace the class attribute with className.