how to prevent rendering when a modal button is clicked - reactjs

I have a component which displays list of jobs. Clicking on each job will open a modal and displays the details of the job. I have a list of candidates displayed in the modal and when i click a button in the modal, the component re renders and the list of candidates are populated twice. how to prevent that. I have called the props below the render() which should not be done. But don't know where to give.
import { connect } from 'react-redux';
import history from '../history'
import moment from 'moment'
import changeStatus from '../store/actions/changeJobStatus'
class EmpJobcontent extends Component {
constructor(props) {
super(props);
this.sendJobId = this.sendJobId.bind(this);
}
state = {
jobid: '', candidatephoneno: '', statusid: ''
}
getJobId = (event) => {
this.setState({
jobid: event.target.getAttribute('name')
}, () => this.sendJobId())
}
closejob = (event) => {
// this.props.changeStatus(event.target.getAttribute("name"))
// var x = document.getElementById("status");
var x = event.target
if (x.value === "close job") {
x.value = "open job";
x.classList.add("btn-primary");
x.classList.remove("btn-danger");
this.props.changeStatus(event.target.getAttribute("name"))
} else {
x.classList.remove("btn-primary");
x.classList.add("btn-danger");
x.value = "close job";
this.props.changeStatus(event.target.getAttribute("name"))
}
}
individualChat = () => {
// history.push('/individualchat')
}
sendJobId = () => {
this.props.empInfo(this.state.jobid)
}
applyJob = () => {
document.getElementById("applyjob").disabled = true;
const { candidatephoneno } = this.props
this.setState({
candidatephoneno: candidatephoneno, jobid: this.state.jobid
}, () => this.sendApplyJob())
}
sendApplyJob = () => {
this.props.applyJob(this.state)
}
render() {
const { joblists } = this.props
const { appliedCandidates } = this.props
return (
<div className=' d-flex flex-wrap justify-content-center' >
{joblists && joblists.map(joblist => {
return (<div >
<div id='cards' ref="jobid" className="card shadow slidercard ">
<div className="row mt-3 d-flex align-items-center" >
<div className="col-md-3">
<div className="profilepic ml-3"></div>
</div>
<div className="text-left col-md-9 ">
<h6>{joblist.companyName}</h6>
</div>
{/* <div className="col-md-3"><i className="far fa-heart heart_color"></i></div> */}
</div>
<div className="m-3">
<h5 className="font-weight-bold pt-3 text-left" id="jobdescription" data-toggle="modal" data-target={`#${joblist.id}`} name={`${joblist.id}`} >{joblist.Description}</h5>
<h5 className="font-weight-bold pt-3 text-left ">{joblist.RatePerHour}</h5>
<div className="row pt-3" id='cardfooter'>
<div className="col-md-2">
<div><i className="fas fa-map-marker-alt"></i></div>
</div>
<div className="col-md-5">
<h6 className="float-left">{joblist.Location}</h6>
</div>
<div className="col-md-5">
<h6 className="float-right">{moment(joblist.postedon.toDate()).fromNow()}</h6>
</div>
</div>
</div>
</div>
<div className="modal fade show" id={joblist.id} ref="jobid" tabIndex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div className="modal-dialog shadow mw-100 w-75" role="document">
<div className="modal-content">
<div className="modal-header">
<button type='button' className="close" data-dismiss="modal">×</button>
</div>
<div className="modal-body">
<div className="jobdesc">
<div className="row mt-3">
<div className="col-md-2">
<div className="jobdescpic ml-3"></div>
</div>
<div className="col-md-8 dialog_body text-left">
<h6>{joblist.companyName}</h6>
<div>
<h5 className="font-weight-bold pt-3 text-left mb-5">{joblist.Title}</h5>
<div className="row d-flex align-items-center">
<div className="col-md-9">
<div className="row d-flex align-items-center border shadow p-2 font-weight-bold " id='rateperhour'>
<div className="col-md-4 text-center">
<p><i className="far fa-clock"></i>1 hour </p>
</div>
<div className="col-md-4 text-center">
<p>{joblist.RatePerHour}</p>
</div>
{/* <div className="col-md-6 ml-auto">
<button type="submit" id='applyjob' className="cta btn btn-primary" onClick={this.applyJob}>apply job</button>
</div> */}
<div className="col-md-4 text-center">
<p>{joblist.status}</p>
</div>
</div>
</div>
<div className="col-md-3">
<div className="d-flex align-items-start justify-content-end">
<h6>{moment(joblist.postedon.toDate()).fromNow()}</h6>
</div>
</div>
</div>
<p className="mt-5">{joblist.Description}</p>
{/* <img src={documentimg} alt="" /> */}
{/* <a href={joblist.Documents} target='_blank'>{joblist.labeltext}</a> */}
</div>
</div>
<div className="col-md-2" id="popupmenu">
<input type='button' id='status' className={joblist.status === "closed" ? "btn btn-primary" : "btn btn-danger"} onClick={this.closejob.bind(this)} name={joblist.id} value={joblist.status === 'closed' ? 'open job' : "close job"} />
{/* <ul>
<li>
<i className="fas fa-ellipsis-h"></i>
<ul>
<li><Link to={`/appliedcandidates`}>status</Link></li>
</ul>
</li>
</ul> */}
</div>
</div>
</div>
</div>
<div class="modal-footer d-block">
<h4 className="text-center p-3 font-weight-bold text-info">applied candidates</h4>
{appliedCandidates && appliedCandidates.map(appliedCandidate => {
if (joblist.id === appliedCandidate.jobid) {
return (
<div className="row pb-3">
<div className="col-md-4 offset-md-1 text-left font-weight-bold">
<p>{appliedCandidate.firstName}</p>
</div>
<div className="col-md-2">
<button type="button" className="btn btn-success card-btn-width">hire</button>
</div>
<div className="col-md-2">
<button type="button" className="btn btn-danger card-btn-width">reject</button>
</div>
<div className="col-md-2">
<button id={appliedCandidate.id} onClick={this.individualChat} type="submit" className="btn btn-info card-btn-width" data-dismiss="modal">chat</button>
</div>
</div>
)
}
})}
</div>
</div>
</div>
</div>
</div>
)
})
}
</div >
)
}
}
const mapStateToProps = (state) => {
console.log(state);
return {
candidatephoneno: state.candidateSignin.phoneno,
appliedCandidates: state.getAppliedCandidates.appliedCandidate
}
}
const mapDispatchToProps = (dispatch) => {
return {
changeStatus: (statusid) => dispatch(changeStatus(statusid)),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(EmpJobcontent)

Related

How to filter Products in React.js?

I am fetching local data through json server. db.json is attached for your reference. When I search any text I want to filter products using heading and when I click on filter checkbox then also I want to filter products by category, size and packs. I have attached every component below for your reference which I am using in this project. Please help me I am using BOOTSTRAP 4.6.0 as UI.
CHECK CODESANDBOX LINK - https://xo6b9.codesandbox.io/product-listing FOR BETTER UNDERSTANDING.
PRODUCT LISTING COMPONENT
import React, { useState, useEffect } from "react";
import PageNotFound from "../other/PageNotFound";
import Loading from "../other/Loading";
import ProductView from "./ProductView";
import SearchResult from "./SearchResult";
import Filter from "./Filter";
const ProductsListing = () => {
const [loading, setLoading] = useState(true);
const [products, setProducts] = useState([]);
const [filters, setFilters] = useState([]);
const [typedValue, setTypedValue] = useState("");
useEffect(() => {
getProductListingData();
}, []);
const getProductListingData = async () => {
try {
const response = await fetch("http://localhost:8000/productListing");
const data = await response.json();
if (data) {
setLoading(false);
setProducts(data.products);
setFilters(data.filters);
} else {
setProducts("PRODUCT LISTING DATA NOT FOUND");
}
} catch (error) {
console.log(error);
}
};
if (loading) {
return <Loading loadingProductListing="Loading Product List" />;
}
const searchFilterFunction = (e) => {
setTypedValue(e);
console.log(typedValue);
if (typedValue !== "") {
const newArray = products.filter((item) => {
return item.heading.indexOf(typedValue) > -1;
});
console.log(newArray);
setProducts(newArray);
} else {
console.log("else block");
setProducts(products);
}
};
return (
<>
{products && filters ? (
<section className="dvMain">
<div className="container-fluid">
<div className="row">
<Filter filters={filters} />
<div className="dvProducts col-lg-6 col-xl-8">
<div className="row">
<SearchResult
searchFilterFunction={(e) => searchFilterFunction(e)}
/>
<div className="dvFilterMobile col-sm-3 col-md-2 d-lg-none text-center text-sm-right mb-3">
<a
href=""
className="btn bg-light w-100"
data-toggle="modal"
data-target="#mobileFiltersModal"
>
<i className="fa fa-filter"></i>Filter
</a>
</div>
</div>
<ProductView products={products} />
</div>
<div className="dvCart col-lg-3 col-xl-2 d-none d-lg-block">
<div className="sticky-top" style={{ top: "100px" }}>
<div className="row">
<div className="col-sm-12 mb-2">
<h5 className="d-inline-block">Cart</h5>
<span className="d-inline-block">106 items</span>
</div>
<div className="dvCartItems col-sm-12 mb-2">
<div className="row">
<div className="scrollbar mr-3">
<div className="item col-sm-12 mb-2 pr-0">
<div className="bg-light pt-2 pb-2">
<div className="col-12">
<h6>Pomegranate</h6>
<p className="f10 text-muted mb-1">250ml</p>
</div>
<div className="col-sm-12">
<div className="d-flex justify-content-between align-items-center">
<div className="addBtn d-flex justify-content-center align-items-center flex-1">
<div className="flex-1 text-center">
<i className="fa fa-minus"></i>
</div>
<div className="flex-3 text-center">
<input
type="text"
className="form-control text-center p-0"
/>
</div>
<div className="flex-1 text-center">
<i className="fa fa-plus"></i>
</div>
</div>
<div className="text-right">
<i className="fa fa-inr"></i>600
</div>
</div>
</div>
<button className="btn btnRemove absolute">
<i className="fa fa-close"></i>
</button>
</div>
</div>
<div className="item col-sm-12 mb-2 pr-0">
<div className="bg-light pt-2 pb-2">
<div className="col-12">
<h6>Coconut Water</h6>
<p className="f10 text-muted mb-1">200ml</p>
</div>
<div className="col-sm-12">
<div className="d-flex justify-content-between align-items-center">
<div className="addBtn d-flex justify-content-center align-items-center flex-1">
<div className="flex-1 text-center">
<i className="fa fa-minus"></i>
</div>
<div className="flex-3 text-center">
<input
type="text"
className="form-control text-center p-0"
/>
</div>
<div className="flex-1 text-center">
<i className="fa fa-plus"></i>
</div>
</div>
<div className="text-right">
<i className="fa fa-inr"></i>80
</div>
</div>
</div>
<button className="btn btnRemove absolute">
<i className="fa fa-close"></i>
</button>
</div>
</div>
<div className="item col-sm-12 mb-2 pr-0">
<div className="bg-light pt-2 pb-2">
<div className="col-12">
<h6>Mango</h6>
<p className="f10 text-muted mb-1">200ml</p>
</div>
<div className="col-sm-12">
<div className="d-flex justify-content-between align-items-center">
<div className="addBtn d-flex justify-content-center align-items-center flex-1">
<div className="flex-1 text-center">
<i className="fa fa-minus"></i>
</div>
<div className="flex-3 text-center">
<input
type="text"
className="form-control text-center p-0"
/>
</div>
<div className="flex-1 text-center">
<i className="fa fa-plus"></i>
</div>
</div>
<div className="text-right">
<i className="fa fa-inr"></i>48
</div>
</div>
</div>
<button className="btn btnRemove absolute">
<i className="fa fa-close"></i>
</button>
</div>
</div>
<div className="item col-sm-12 mb-2 pr-0">
<div className="bg-light pt-2 pb-2">
<div className="col-12">
<h6>Sugarcane</h6>
<p className="f10 text-muted mb-1">250ml</p>
</div>
<div className="col-sm-12">
<div className="d-flex justify-content-between align-items-center">
<div className="addBtn d-flex justify-content-center align-items-center flex-1">
<div className="flex-1 text-center">
<i className="fa fa-minus"></i>
</div>
<div className="flex-3 text-center">
<input
type="text"
className="form-control text-center p-0"
/>
</div>
<div className="flex-1 text-center">
<i className="fa fa-plus"></i>
</div>
</div>
<div className="text-right">
<i className="fa fa-inr"></i>64
</div>
</div>
</div>
<button className="btn btnRemove absolute">
<i className="fa fa-close"></i>
</button>
</div>
</div>
<div className="item col-sm-12 mb-2 pr-0">
<div className="bg-light pt-2 pb-2">
<div className="col-12">
<h6>Life</h6>
<p className="f10 text-muted mb-1">250ml</p>
</div>
<div className="col-sm-12">
<div className="d-flex justify-content-between align-items-center">
<div className="addBtn d-flex justify-content-center align-items-center flex-1">
<div className="flex-1 text-center">
<i className="fa fa-minus"></i>
</div>
<div className="flex-3 text-center">
<input
type="text"
className="form-control text-center p-0"
/>
</div>
<div className="flex-1 text-center">
<i className="fa fa-plus"></i>
</div>
</div>
<div className="text-right">
<i className="fa fa-inr"></i>120
</div>
</div>
</div>
<button className="btn btnRemove absolute">
<i className="fa fa-close"></i>
</button>
</div>
</div>
<div className="item col-sm-12 mb-2 pr-0">
<div className="bg-light pt-2 pb-2">
<div className="col-12">
<h6>Valencia Orange</h6>
<p className="f10 text-muted mb-1">1litre</p>
</div>
<div className="col-sm-12">
<div className="d-flex justify-content-between align-items-center">
<div className="addBtn d-flex justify-content-center align-items-center flex-1">
<div className="flex-1 text-center">
<i className="fa fa-minus"></i>
</div>
<div className="flex-3 text-center">
<input
type="text"
className="form-control text-center p-0"
/>
</div>
<div className="flex-1 text-center">
<i className="fa fa-plus"></i>
</div>
</div>
<div className="text-right">
<i className="fa fa-inr"></i>240
</div>
</div>
</div>
<button className="btn btnRemove absolute">
<i className="fa fa-close"></i>
</button>
</div>
</div>
<div className="item col-sm-12 mb-2 pr-0">
<div className="bg-light pt-2 pb-2">
<div className="col-12">
<h6>Trim</h6>
<p className="f10 text-muted mb-1">250ml</p>
</div>
<div className="col-sm-12">
<div className="d-flex justify-content-between align-items-center">
<div className="addBtn d-flex justify-content-center align-items-center flex-1">
<div className="flex-1 text-center">
<i className="fa fa-minus"></i>
</div>
<div className="flex-3 text-center">
<input
type="text"
className="form-control text-center p-0"
/>
</div>
<div className="flex-1 text-center">
<i className="fa fa-plus"></i>
</div>
</div>
<div className="text-right">
<i className="fa fa-inr"></i>120
</div>
</div>
</div>
<button className="btn btnRemove absolute">
<i className="fa fa-close"></i>
</button>
</div>
</div>
<div className="item col-sm-12 mb-2 pr-0">
<div className="bg-light pt-2 pb-2">
<div className="col-12">
<h6>Aloe Lemonade</h6>
<p className="f10 text-muted mb-1">250ml</p>
</div>
<div className="col-sm-12">
<div className="d-flex justify-content-between align-items-center">
<div className="addBtn d-flex justify-content-center align-items-center flex-1">
<div className="flex-1 text-center">
<i className="fa fa-minus"></i>
</div>
<div className="flex-3 text-center">
<input
type="text"
className="form-control text-center p-0"
/>
</div>
<div className="flex-1 text-center">
<i className="fa fa-plus"></i>
</div>
</div>
<div className="text-right">
<i className="fa fa-inr"></i>40
</div>
</div>
</div>
<button className="btn btnRemove absolute">
<i className="fa fa-close"></i>
</button>
</div>
</div>
</div>
</div>
</div>
<div className="dvCartEmpty col-12 d-none">
<h6>Cart is Empty.</h6>
<p className="f12">
All Good No Bad! Go ahead, order some items from the
menu.
</p>
<img
src="images/cart-empty.png"
className="img-fluid"
width="200"
alt=""
/>
</div>
<div className="col-sm-12 mb-2">
<div className="d-flex justify-content-between">
<div>
<h6>Subtotal</h6>
</div>
<div>
<p>
<i className="fa fa-inr"></i>1,312.00
</p>
</div>
</div>
<p className="f12">Extra charges may apply.</p>
</div>
<div className="col-sm-12 mb-2">
<a href="checkout.html" className="btn btnPrimary w-100">
Proceed
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
) : (
<PageNotFound />
)}
</>
);
};
export default ProductsListing;
PRODUCT VIEW COMPONENT
import React from "react";
const ProductView = ({ products }) => {
return (
<>
<div className="dvProductView row">
{products &&
products.map((product) => {
const {
id,
heading,
description,
detailsTable,
category,
img,
packs,
price,
size,
} = product;
return (
<div key={id} className="col-6 col-md-4 col-lg-6 col-xl-3 mb-4">
<div className="border border-light shadow-sm p-1 h-100">
<div>
<div className="bg-light text-center pt-2 pb-2 mb-1">
<a className="d-inline-block" href="">
<img src={img} className="img-fluid" alt={heading} />
</a>
</div>
<h6 className="text-center">{heading}</h6>
</div>
<div className="d-flex justify-content-between mb-1">
<div className="size">
<p>{size}</p>
</div>
<div className="discount-price mr-2">
<span>
<i className="fa fa-inr"></i>
<span>{price}</span>
</span>
</div>
</div>
<div className="text-center">
<button
className="btn btnSecondary w-100"
href="detail.html"
>
Add to Bag
</button>
</div>
</div>
</div>
);
})}
</div>
</>
);
};
export default ProductView;
SEARCH RESULT COMPONENT
import React, { useState } from "react";
const SearchResult = ({ searchFilterFunction }) => {
// console.log(searchFilterFunction);
// const [searchText, setSearchText] = useState("");
// console.log(searchText);
return (
<>
<div className="dvSearch col-sm-9 col-md-10 col-lg-12 mb-3">
<form className="position-relative">
<input
// value={searchText}
onChange={(e) => searchFilterFunction(e.target.value)}
type="text"
className="form-control"
placeholder="Search - orange, mango, etc."
/>
<button className="btn btnSearch position-absolute">
<i className="fa fa-search"></i>
</button>
</form>
</div>
</>
);
};
export default SearchResult;
FILTER COMPONENT
import React from "react";
const Filter = ({ filters }) => {
return (
<>
<div className="dvFilters col-lg-3 col-xl-2 d-none d-lg-block text-right">
<div className="sticky-top" style={{ top: "100px" }}>
{filters.map((item, index) => {
const { id, heading, submenu } = item;
return (
<div key={id} className="dvPackages row">
<div className="col-sm-12">
<h5 className={`${index === 0 ? "" : "mt-3"}`}>{heading}</h5>
</div>
{submenu.map((item) => {
const { id, name } = item;
return (
<div key={id} className="col-sm-12">
<label className="d-inline-block">
<span className="badge badge-light">05</span>
<span>{name}</span>
<input type="checkbox" />
</label>
</div>
);
})}
</div>
);
})}
</div>
</div>
</>
);
};
export default Filter;
DB.JSON
{
"productListing": {
"filters": [
{
"id": 1,
"heading": "Packages",
"submenu": [
{ "id": 1, "name": "Subscriptions" },
{ "id": 2, "name": "Value Packs" }
]
},
{
"id": 2,
"heading": "Categories",
"submenu": [
{ "id": 1, "name": "Juices" },
{ "id": 2, "name": "Cleanses" },
{ "id": 3, "name": "Almond Milk" },
{ "id": 4, "name": "protein MilkShake" }
]
},
{
"id": 3,
"heading": "Size",
"submenu": [
{ "id": 1, "name": "200ml" },
{ "id": 2, "name": "250ml" },
{ "id": 3, "name": "410ml" }
]
},
{
"id": 4,
"heading": "Packs",
"submenu": [
{ "id": 1, "name": "pack of 2" },
{ "id": 2, "name": "pack of 4" },
{ "id": 3, "name": "pack of 6" },
{ "id": 4, "name": "pack of 8" },
{ "id": 5, "name": "pack of 10" },
{ "id": 6, "name": "pack of 12" },
{ "id": 7, "name": "pack of 14" },
{ "id": 8, "name": "pack of 16" },
{ "id": 9, "name": "pack of 18" },
{ "id": 10, "name": "pack of 20" },
{ "id": 11, "name": "pack of 24" },
{ "id": 12, "name": "pack of 30" },
{ "id": 13, "name": "pack of 36" }
]
}
],
"products": [
{
"id": 1,
"description": "Valencia Orange Every athlete’s go to natural energy drink; Coconut Water is a complete win-win for your everyday rehydration needs. #iaminlovewiththecoco!",
"category": "juices",
"img": "https://static.wixstatic.com/media/2c0034_5b8e230643ee4b6cbb1ae55088b40d50~mv2.png",
"heading": "Valencia Orange",
"size": "250ml",
"packs": 0,
"price": 80
},
{
"id": 2,
"description": "Valencia Orange Every athlete’s go to natural energy drink; Coconut Water is a complete win-win for your everyday rehydration needs. #iaminlovewiththecoco!",
"category": "juices",
"img": "https://static.wixstatic.com/media/2c0034_e8d3fce1719f402797ddaaa555c094e4~mv2.png",
"heading": "Valencia Orange",
"size": "1litre",
"packs": 0,
"price": 240
},
{
"id": 3,
"description": "Trim Every athlete’s go to natural energy drink; Coconut Water is a complete win-win for your everyday rehydration needs. #iaminlovewiththecoco!",
"category": "juices",
"img": "https://static.wixstatic.com/media/2c0034_7534300a0eb04f75b0170b7eb8da71aa~mv2.png",
"heading": "Trim",
"size": "250ml",
"packs": 0,
"price": 120
}
]
}
}
IN THE PRODUCT LISTING COMPONENT
Create a new state and name it allProducts as below :-
const [allProducts, setAllProducts] = useState([]);
and pass data from async function :-
const getProductListingData = async () => {
try {
const response = await fetch("http://localhost:8000/productListing");
const data = await response.json();
if (data) {
setLoading(false);
setProducts(data.products);
//send all the products
setAllProducts(data.products);
setFilters(data.filters);
} else {
setProducts("PRODUCT LISTING DATA NOT FOUND");
}
} catch (error) {
console.log(error);
}
};
and then set in else block
const searchFilterFunction = (e) => {
const inputValue = e;
console.log(inputValue);
if (inputValue !== "") {
console.log(inputValue);
const newArray = products.filter((item) => {
return item.heading.toLowerCase().match(inputValue);
});
console.log(inputValue);
setProducts(newArray);
} else {
// set allProducts here
setProducts(allProducts);
}
};

Cannot fetch value to display item

i was trying to fetch the value of the functions(increment, decrement,remove) and the value of the item(id, price...) to display in the cartItem but it isn't working, is there anything wrong with my params? please help me to fix it! Thank you so much!
CartList.js:
import React from "react";
import CartItem from "./CartItem";
export default function CartList(props) {
const { items } = props;
console.log(props, "inside cart");
return (
<div>
{items.cart.map((item) => (
<CartItem key={item.id} item={item} />
))}
</div>
);
}
CartItem.js:
import React from "react";
function CartItem(props) {
const { id, title, img, price, total, count } = props.item;
const { increment, decrement, removeItem } = props.value;
return (
<div className="row my-1 text-capitalize text-center">
<div className="col-10 mx-auto col-lg-2">
<img
src={img}
style={{ width: "5rem", heigth: "5rem" }}
className="img-fluid"
alt=""
/>
</div>
<div className="col-10 mx-auto col-lg-2 ">
<span className="d-lg-none">product :</span> {title}
</div>
<div className="col-10 mx-auto col-lg-2 ">
<strong>
<span className="d-lg-none">price :</span> ${price}
</strong>
</div>
<div className="col-10 mx-auto col-lg-2 my-2 my-lg-0 ">
<div className="d-flex justify-content-center">
<div>
<span className="btn btn-black mx-1">-</span>
<span className="btn btn-black mx-1">{count}</span>
<span className="btn btn-black mx-1">+</span>
</div>
</div>
</div>
<div className="col-10 mx-auto col-lg-2 ">
<div className=" cart-icon" onClick={() => removeItem(id)}>
<i className="fas fa-trash" />
</div>
</div>
<div className="col-10 mx-auto col-lg-2 ">
<strong>item total : ${total} </strong>
</div>
</div>
);
}
export default CartItem;
Sandbox link for better observation:https://codesandbox.io/s/cart-code-addict-forked-rrkuz?file=/src/cart/CartItem.js

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>
))}

loop through api json data react js

i konw there are similar question to this but i couldn't find the solution.
i'm trying to loop through this "div" with data coming from django rest api (JSON format)
async componentDidMount() {
const response = await fetch('/api/Post');
const data = await response.json();
this.setState({
posts: data.data[0],
loading: false
});
}
<div class="row">
<div class="col-md-6 col-6 paddding animate-box" data-animate-effect="fadeIn">
<div class="fh5co_suceefh5co_height_2"><img src={image} alt="img"/>
<div class="fh5co_suceefh5co_height_position_absolute"></div>
<div class="fh5co_suceefh5co_height_position_absolute_font_2">
<div class=""> <i class="fa fa-clock-o"></i> {date_posted} </div>
<div class=""> {title} </div>
</div>
</div>
</div></div>
i tried to use "map" but i'm not sure how
function renderposts() {
const postList = [];
for(let i = 0; i < this.state.posts.length; i++) {
let title = `${this.state.posts[i].title}`;
let image = this.state.posts[i].image;
let date_posted = this.state.posts[i].date_posted;
let key = this.state.posts[i].id.value;
postList.push(<Post
<div class="row">
<div class="col-md-6 col-6 paddding animate-box" data-animate-effect="fadeIn">
<div class="fh5co_suceefh5co_height_2"><img src={image} alt="img"/>
<div class="fh5co_suceefh5co_height_position_absolute"></div>
<div class="fh5co_suceefh5co_height_position_absolute_font_2">
<div class=""> <i class="fa fa-clock-o"></i> {date_posted} </div>
<div class=""> {title} </div>
</div>
</div>
</div></div>
/>);
}
return postList;
}
try like this in your render method:
{this.state.posts.map((post) => {
return (
<div
class="col-md-6 col-6 paddding animate-box"
data-animate-effect="fadeIn"
>
<div class="fh5co_suceefh5co_height_2">
<img src={post.image} alt="img" />
<div class="fh5co_suceefh5co_height_position_absolute"></div>
<div class="fh5co_suceefh5co_height_position_absolute_font_2">
<div class="">
<a href="#" class="color_fff">
{" "}
<i class="fa fa-clock-o"></i> {post.date_posted}{" "}
</a>
</div>
<div class="">
<a href="single.html" class="fh5co_good_font_2">
{" "}
{post.title}{" "}
</a>
</div>
</div>
</div>
</div>
);
})}
here is a codesandbox example using hooks:
codesandbox
I assume that data.data[0] is an array of data. In React, when you want to loop through a array of data, always use method that return a clone of your data such as map or filter to avoid problem with immutability. Here's the specific code for your problem:
const postList = this.state.posts.map((post) => {
// Destructuring assignment
const { title, image, date_posted } = post;
const key = post.id.value;
return (
<div class="row">
<div
class="col-md-6 col-6 paddding animate-box"
data-animate-effect="fadeIn"
>
<div class="fh5co_suceefh5co_height_2">
<img src={image} alt="img" />
<div class="fh5co_suceefh5co_height_position_absolute"></div>
<div class="fh5co_suceefh5co_height_position_absolute_font_2">
<div class="">
<a href="#" class="color_fff">
{' '}
<i class="fa fa-clock-o"></i> {date_posted}{' '}
</a>
</div>
<div class="">
<a href="single.html" class="fh5co_good_font_2">
{' '}
{title}{' '}
</a>
</div>
</div>
</div>
</div>
</div>
);
});

React - How to pass props down for the .map function when using functional components

How can I pass the props from the ProductFeatures to the renderFeatures function ?
Below is a sample code:
const renderFeatures = (feature) => {
return (
<div key={feature.productFeatureTypeId} className="panel panel-default">
<div className="panel-heading">
<div className="row row-no-border row-h-10">
<div className="col-xs-10">
<a
className="accordion-toggle"
data-toggle="collapse"
href={"#" + feature.productFeatureTypeId}
>
<h4 className="panel-title">{feature.productFeatureTypeId}</h4>
</a>
</div>
<div className="col-xs-2 text-right font-size-16">
<span className="glyphicon glyphicon-circle-arrow-down"></span>
</div>
</div>
</div>
<div
id={feature.productFeatureTypeId}
className="panel-collapse collapse in"
>
<div className="panel-body">
{feature.productFeaturesDescription.map(renderFeatureObjItem)}
</div>
</div>
</div>
);
};
const ProductFeatures = (props) => {
let mappedProductFeaturesMembers = getMappedProductFeaturesMembers(
props.product.productFeatureMembers
);
return (
<div className="panel-group" id="accordion">
{mappedProductFeaturesMembers.map(renderFeatures)}
</div>
);
};
Note that all this code is inside one file named ProductFeatures.js and I am using functional components.
You can just pass it in the rednerFeatures like this:
const renderFeatures = (feature, props) => { // Accept both feature and props
return (
<div key={feature.productFeatureTypeId} className="panel panel-default">
<div className="panel-heading">
<div className="row row-no-border row-h-10">
<div className="col-xs-10">
<a
className="accordion-toggle"
data-toggle="collapse"
href={"#" + feature.productFeatureTypeId}
>
<h4 className="panel-title">{feature.productFeatureTypeId}</h4>
</a>
</div>
<div className="col-xs-2 text-right font-size-16">
<span className="glyphicon glyphicon-circle-arrow-down"></span>
</div>
</div>
</div>
<div
id={feature.productFeatureTypeId}
className="panel-collapse collapse in"
>
<div className="panel-body">
{feature.productFeaturesDescription.map(renderFeatureObjItem)}
</div>
</div>
</div>
);
};
const ProductFeatures = (props) => {
let mappedProductFeaturesMembers = getMappedProductFeaturesMembers(
props.product.productFeatureMembers
);
return (
<div className="panel-group" id="accordion">
{mappedProductFeaturesMembers.map(feature => renderFeatures(feature, props))} // Pass props here too
</div>
);
};

Resources