'how to add function on event onclick on array.map in react js
class ProjectFirestoreData extends Component {
constructor(props) {
super(props);
this.userDelete = this.userDelete.bind(this)
}
userDelete(authorId){
console.log(authorId)
}
render() {
let {firestore} = this.props;
if(!Array.isArray(firestore) || !firestore.length ){
return (
<div>
<h1>Loading</h1>
</div>
)
}
else{
return (
<div className="col-md-8">
<div className="row">
{
firestore.map(function(index, elem) {
return (
<div className="col-md-6 p-3" key={index.name} >
<div className="card">
<img className="card-img-top" src="..." alt="Card" />
<div className="card-body">
<h5 className="card-title text-dark">AuthorName is : {index.authorFirstName} </h5>
<p className="card-text text-dark">Some quick example text to build on the card title and make up the bulk of the card's content.
</p>
<Link to={`/userdetails/${index.authorId}`} className="btn btn-primary">Show Full Data</Link>
<button type="button" class="btn btn-dark" onClick={() => this.userDelete(index.authorId)}>Dark</button>
</div>
</div>
</div>
)
})
}
</div>
</div>
)
}
}
}
onclick event is working after the array.map , but it is not working under the array.map is there any way of achieving it ? i have tried adding
<button type="button" class="btn btn-dark" onClick={() =>this.userDelete(index.authorId)}>Dark</button>
after array.map and it is working fine . but under array.map it is not working . the error says
TypeError: Cannot read property 'userDelete' of undefined
Solution 1:[1]
onclick event inside map:
<div className={styles.file_content_show}>
{this.state.fileinformation.map((item)=>{
return (
<p className={styles.file_name_show}>{item.file_name}
<span className={styles.file_size_date}> ({item.file_size} | {item.file_modified_date}) <img src={attachmentdelete_logo} className={styles.attachmentdelete_logo} onClick={this.deleteattachment.bind(item.file_size)}/></span>
</p>
);
})}
</div>
Function is this:
@autobind
private deleteattachment(file){
var a=file;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nimantha |
