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.
Related
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>
})
}
I have data that I am looping through and I have a slight issue with a dropdown menu. Whenever I click the dropdown button for a single post all the other posts open. And I don't know to solve it.
Here is the React code
const Post = () {
const [open, setOpen] = useState(false)
return(
{posts.map((post) => {
return (
<div className="card" key={post.postId}>
<div className="card-header">
<div className="card-header__avatar">
<img
src="https://source.unsplash.com/user/erondu/40x40"
alt=""
/>
</div>
<div className="card-header__username">
<span>
<strong>
{post.firstname} {post.lastname}
</strong>
</span>
<br />
<span>
<small>{date}</small>
</span>
</div>
<div
className="card-header__moreBtn"
onClick={() => setOpen(!open)}
>
<img src={More} alt="" />
{open && ( ------> here is where the problem comes
<div class="dropdown-wrapper">
<ul class="dropdown-menu">
<li class="dropdown-menu__item">
<Link href="#d" onClick={deletePost}>Edit</Link>
</li>
<li class="dropdown-menu__item">
<Link className="dropdown-menu__item__link" onClick={deletePost}>Delete</Link>
</li>
</ul>
</div>
)}
</div>
</div>
<div className="postDescription">
<p>{post.postDescription}</p>
</div>
<div className="imgPost">
<img src={post.image} alt="" />
</div>
</div>
)
})}
)
}
Here is a picture
Any help will suffice and I appreciate your time.
You're using the same state value for all items in your loop, so naturally they are going to all follow the same directive.
I would recommend creating a PostItem component that maintains its own state. Something like this:
const PostItem = ({post}) => {
const [open, setOpen] = useState(false)
return (
<div className="card" key={post.postId}>
<div className="card-header">
<div className="card-header__avatar">
<img
src="https://source.unsplash.com/user/erondu/40x40"
alt=""
/>
</div>
<div className="card-header__username">
<span>
<strong>
{post.firstname} {post.lastname}
</strong>
</span>
<br />
<span>
<small>{date}</small>
</span>
</div>
<div
className="card-header__moreBtn"
onClick={() => setOpen(!open)}
>
<img src={More} alt="" />
{open && (
<div class="dropdown-wrapper">
<ul class="dropdown-menu">
<li class="dropdown-menu__item">
<Link href="#d" onClick={deletePost}>Edit</Link>
</li>
<li class="dropdown-menu__item">
<Link className="dropdown-menu__item__link" onClick={deletePost}>Delete</Link>
</li>
</ul>
</div>
)}
</div>
</div>
<div className="postDescription">
<p>{post.postDescription}</p>
</div>
<div className="imgPost">
<img src={post.image} alt="" />
</div>
</div>
)
})
}
const AllPosts = ({posts}) {
return(
{posts.map(post => <PostItem post={post} />
)
}
Now each PostItem has a separate, internal instance of open in its own state and will act independently from the others.
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>
);
});
I have 4 components in my project, that have the APIs, and there information.
the App.js includes the APIs:
This is in my Country.js Component
render() {
const DataGroup = this.props.countries.map((county) => {
return <InfoData info={county} />;
});
const DataGroupAll = this.props.countriesAll.map((country) => {
return <InfosData infos={country} />;
});
return (
<div>
{DataGroup}
{DataGroupAll}
</div>
);
}
and the InfoData.js
<div class="card-columns">
<div class="card-body">
<h5 class="card-title">Date : {this.props.info.updated_at}</h5>
<p class="card-text">Confirmed : {this.props.info.today.confirmed}</p>
<p class="card-text">Deaths : {this.props.info.today.deaths}</p>
</div>
</div>
and the InfosData.js
<div class="card-deck">
<div class="card">
<img src={this.props.infos.flag} width="180" height="130" />
<div class="card-body">
<h4 class="card-title">Name : {this.props.infos.name}</h4>
<p class="card-text">Capital : {this.props.infos.capital}</p>
<p class="card-text">
Currency :
{this.props.infos.currencies.map((country) => {
return country.code;
})}
</p>
<p class="card-text">
Languages :
{this.props.infos.languages.map((country) => {
return country.name + ',';
})}
</p>
<p class="card-text">Timezones : {this.props.infos.timezones}</p>
</div>
</div>
</div>
but all the information I got will be in separate cards, how can I combine them by the country code ?
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.