How to display date from Mongodb as String within map in React? - reactjs

I have date stored in Mongodb which diplays as 2005-12-03T18:30:00.000Z in frontend. But I need it in string format.
I tried using var date = new Date(2005-12-03T18:30:00.000Z).toDateString but I don't exactley know where to put this line. Please help.
{
orders.map((val, key)=>{
return <div className='bg-light mx-3 my-2 p-4 rounded-4 border border-info border-4' key={key}>
<div className='d-inline-block mx-2'>
<span className='fs-5 fw-bold'>{val.orderId}</span>
</div>
<div className='d-inline-block mx-3'>
<span className='fs-5 fw-bold'>{val.date}</span> //<--------I want date in this line
</div>
<div className='d-inline-block mx-4'>
<span className='fs-5 fw-bold'>{val.orderType}</span>
</div>
<button onClick={() => navigate(`/update/${val._id}`)} className="nav-link">Edit</button>
<button onClick={() => deleteOrder(val._id)} className="nav-link">Delete</button>
</div>
})
}

Maybe val.date part.
{
orders.map((val, key)=>{
return <div className='bg-light mx-3 my-2 p-4 rounded-4 border border-info border-4' key={key}>
<div className='d-inline-block mx-2'>
<span className='fs-5 fw-bold'>{val.orderId}</span>
</div>
<div className='d-inline-block mx-3'>
<span className='fs-5 fw-bold'>{new Date(val.date).toDateString()}</span> //<--------I want date in this line
</div>
<div className='d-inline-block mx-4'>
<span className='fs-5 fw-bold'>{val.orderType}</span>
</div>
<button onClick={() => navigate(`/update/${val._id}`)} className="nav-link">Edit</button>
<button onClick={() => deleteOrder(val._id)} className="nav-link">Delete</button>
</div>
})
}

Related

BootStrap 5 React Js 4 products in a row not getting displayed

I'm a beginner in React Js, and I'm using React Js with BootStrap 5.2.0
My product cards are not getting displayed in a row
I want to display 4 product cards in a row.
Adding Codes:
Home Page code:
<div className="container-fluid mb-2">
<Carousel />
<div className="mt-2">
<div className="row">
<div className="col-md-2">
<GetAllCategories />
</div>
<div className="col-md-10">
<div className="row row-cols-1 row-cols-md-4 g-4">
<div className="col">
{products.map((product) => {
return <ProductCard item={product} />;
})}
</div>
</div>
</div>
</div>
</div>
</div>
PRODUCT CARD CODE:
const ProductCard = (product) => {
return (
<div class="card border-color rounded-card card-hover product-card custom-bg">
<img
src={"http://localhost:8080/api/product/" + product.item.imageName}
class="card-img-top rounded mx-auto d-block m-2"
alt="img"
style={{
maxHeight: "270px",
maxWidth: "100%",
width: "auto",
}}
/>
<div class="card-body text-color">
<h5 class="card-title d-flex justify-content-between">
<div>
<b>{product.item.title}</b>
</div>
<CategoryNavigator
item={{
id: product.item.category.id,
title: product.item.category.title,
}}
/>
</h5>
<p className="card-text">
<b>{product.item.description}</b>
</p>
</div>
<div class="card-footer">
<div className="text-center text-color">
<p>
<span>
<h4>Price : ₹{product.item.price}</h4>
</span>
</p>
</div>
<div className="d-flex justify-content-between">
<Link
to={`/product/${product.item.id}/category/${product.item.category.id}`}
className="btn bg-color custom-bg-text"
>
Add to Cart
</Link>
<p class="text-color">
<b>
<i>Stock :</i> {product.item.quantity}
</b>
</p>
</div>
</div>
</div>
);
};
export default ProductCard;
From the past 4 days, I'm struggling to resolve this issue.
Please help me to fix this.
Thank You
You need to move <div className="col"> from home page to ProductCard as first element in return statement. Sample code at https://codesandbox.io/s/falling-thunder-swzukd

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

TypeError: Cannot read property 'title' of undefined on React

Consistently getting TypeError: Cannot read property 'title' of undefined when trying to load of my page. I am certain its related to my props but cannot figure what I am doing wrong.
I've tried going through every single prop and editing it but I continue to get the same error just for the next "person title" after.
import React from "react";
const Personcard = props => {
const handleUpdate = () => {
props.handleEdit(props.person.id);
};
return (
<div className="container">
<div className="containerUsers">
<div className="card">
<img
// src={props.person.primaryImage.imagineUrl}
id="primaryImageUsers"
alt=""
/>
<div className="card-body">
<div className="card-title">
<h2>
{props.person.title === "Mr" && (
<span id="titleUsers"> {props.person.title}</span>
)}
</h2>
</div>
</div>
<div className="card-text">
<h4>
<span id="headlineUsers" value={props.person.headline}>
{" "}
</span>
</h4>
<p>
<span id="summaryUsers" value={props.person.summary}>
{" "}
</span>
</p>
<p>
<span value={props.person.skills}> </span>
</p>
</div>
<button
type="button"
className="btn btn-warning"
onClick={handleUpdate}
>
{" "}
Update{" "}
</button>
<button type="button" className="btn btn-danger">
Delete
</button>
</div>
</div>
</div>
);
};
My goal is to display registered users on a homepage.
What you actually need to do is check for props.person whether it exists or not.
There are two cases:
It exists: we return the containerUsers.
It doesn't: we return a loading compoent.
We can check for it as this props.person ? true:false, true will be where we return the containerUsers, false where we will be returning the loading component.
import React from "react";
const Personcard = props => {
const handleUpdate = () => {
props.handleEdit(props.person.id);
};
return (andleUpdate = () => {
props.handleEdit(props.person.id);
};
return (
<div className="container">
{
props.person ? (
<div className="containerUsers">
<div className="card">
<img
// src={props.person.primaryImage.imagineUrl}
id="primaryImageUsers"
alt=""
/>
<div className="card-body">
<div className="card-title">
<h2>
{props.person.title === "Mr" && (
<span id="titleUsers"> {props.person.title}</span>
)}
</h2>
</div>
</div>
<div className="card-text">
<h4>
<span id="headlineUsers" value={props.person.headline}>
{" "}
</span>
</h4>
<p>
<span id="summaryUsers" value={props.person.summary}>
{" "}
</span>
</p>
<p>
<span value={props.person.skills}> </span>
</p>
</div>
<button
type="button"
className="btn btn-warning"
onClick={handleUpdate}
>
{" "}
Update{" "}
</button>
<button type="button" className="btn btn-danger">
Delete
</button>
</div>
</div>
</div>
) : null
}
);
};
In the code I provided, instead of null, return a loading component if you want.
it's the last line in the return function. should be: ( <Loading /> ) for example.
So, I did this because, person is not defined at the first mount of the component, that's why we checked for it.
Currently this will solve the problem, but I prefer if you pass a default value for props.person from the parent component, it can be a plain object {} with nothing without it.

Change fields names in React

I currently have this code, and in a spam it calls {image.processamento.result}
renderImgs() {
const { images, loadingFetchImages } = this.state;
if (loadingFetchImages) {
return <Loading />;
}
return images.map(image => (
<div key={image.processamento.id} className="col-2">
<div role="button" tabIndex={0} onKeyPress={() => this.checkImage(image.processamento.id)} onClick={() => this.checkImage(image.processamento.id)} className={`lista-img-validar ${image.check ? 'active' : ''}`}>
<figure>
<img src={image.public_url} id="image-authorize" className="img-responsive" alt="Imagem da prova" />
</figure>
<figcaption>
<div className="col-12">
<article className="text-left">
<span className="validador-txt-destaque">{image.processamento.co_inscricao}</span>
</article>
</div>
<div className="col-12">
<article className="text-left mt-2">
<span className="validador-txt-destaque-silver">Lote: </span>
<span>{image.processamento.batch}</span>
</article>
</div>
<div className="col-12">
<article className="text-left mt-2">
<span className="validador-txt-destaque-silver">Situação: </span>
<span>{image.processamento.result}</span>
</article>
</div>
</figcaption>
</div>
</div>
));
}
{image.processamento.result} can return 3 values, "essay", "inssuficient" and "blank", all that I want to do is change this names when I'm rendering the images to the user, for ex. I want that "blank" becomes "Sem texto."
I'm confused because inside a return I can't use conditionals like if else etc, can someone help me?
renderImgs() {
const { images, loadingFetchImages } = this.state;
if (loadingFetchImages) {
return <Loading />;
}
const getFriendlyName = function(name) {
if(name == "blank"){
return "Sem texto
}
return name
}
return images.map(image => (
<div key={image.processamento.id} className="col-2">
<div role="button" tabIndex={0} onKeyPress={() => this.checkImage(image.processamento.id)} onClick={() => this.checkImage(image.processamento.id)} className={`lista-img-validar ${image.check ? 'active' : ''}`}>
<figure>
<img src={image.public_url} id="image-authorize" className="img-responsive" alt="Imagem da prova" />
</figure>
<figcaption>
<div className="col-12">
<article className="text-left">
<span className="validador-txt-destaque">{image.processamento.co_inscricao}</span>
</article>
</div>
<div className="col-12">
<article className="text-left mt-2">
<span className="validador-txt-destaque-silver">Lote: </span>
<span>{image.processamento.batch}</span>
</article>
</div>
<div className="col-12">
<article className="text-left mt-2">
<span className="validador-txt-destaque-silver">Situação: </span>
<span>{getFriendlyName(image.processamento.result)}</span>
</article>
</div>
</figcaption>
</div>
</div>
));
}
Do like this.
<span>{image.processamento.result == "blank" ? "Sem texto" : image.processamento.result }</span>
You could do this from many ways, I think the right way you can do this:
const status = [
blank:"some blank text",
essay:"some essay text",
inssuficient:"some inssuficient text"
];
<span>{status[image.processamento.result]}</span>
Ternary operators are essential in JSX. They can also be chained, much like if/elses,
This would be valid:
<span>{image.processamento.result === 'blank' ? "Sem texto" : image.processamento.result === 'insufficient' ? 'Não suficiente' : image.processamento.result }</span>
Of course, this can all be abstracted before returning the jsx tag into if statements. Inside your map, instead of a shorthand return, you would just do an explicit return, and declare a variable representing the result before that. But that's really just a matter of preference.

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