0

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?

3
  • It's correct. Add ur PostItem code. Commented Apr 29, 2018 at 2:50
  • what do you mean? when i click on a postitem, i dont get anything logged. When I make a new separate component with just the onclick function, it logs. Commented Apr 29, 2018 at 2:51
  • maybe something wrong with your PostItem. Commented Apr 29, 2018 at 2:53

1 Answer 1

1

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)} /> 
Sign up to request clarification or add additional context in comments.

2 Comments

so i tried this, and that definitely makes sense in how you explain passing a function is exactly the same as passing an array or variable. now when i do as you said. it doesnt console.log anything, but the props of all of the children now contain an onClick method
check your PostItem and make sure the onClick is passed into a component that's clickable, eg const PostItem = ({ onClick, title }) => <div><h1 {...{ onClick }}>{title}</h1></div>;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.