Reputation: 39
I want to fire an onClick function when I click on any of my children "postItem" components. With what I have now, the clicked components won't do anything, unless the onClick function is outside the map function (such as in a new separate component)
import React, { Component } from "react";
import axios from "axios";
import PostItem from "./postItem";
import "../styles/socialFeed.css";
class SocialFeed extends Component {
constructor(props) {
super(props);
this.state = { posts: [] };
this.showBox = this.showBox.bind(this);
}
showBox(postItem) {
console.log(this);
}
componentDidMount() {
this.Posts();
}
Posts() {
axios
.get(
"randomapi"
)
.then(res => {
const posts = res.data.data;
this.setState({ posts });
});
}
render() {
let { posts } = this.state;
let allPosts = posts.map(post => (
<PostItem key={post.id} {...post} onClick={this.showBox} />
));
return <div className="social-feed">{allPosts}</div>;
}
}
export default SocialFeed;
is it incorrect to pass a function through a map?
Upvotes: 0
Views: 2489
Reputation: 6898
This has nothing to do with your onClick
being inside a map. Remember that when you're thinking in ecma, functions are first-class: passing a function around as a prop is no different than a string or an array, and those are okay to map, right?
The problem appears to be the arguments passed to the SocialFeed#showBox
method. Your method is defined as taking showItem
as the arg, but onClick
will pass the React SyntheticEvent
object as its first arg. While you technically can get the target
from that, this may or may not be what you want to show the box (probably not).
What you'll usually want to do, is pass in an argument to the event handler, e.g.:
<PostItem key={post.id} {...post} onClick={() => this.showBox(post)} />
Upvotes: 1