-2

Hi I am building a frontend in react and I am rendering a List of places that I get from google maps api. I want each place to fire an action on onClick. If I don't pass any value it works, if I pass the id of the place that I get from props than onClick is fired when the list item is rendered leading to an error. Here is the list component

import {ListGroup} from "react-bootstrap";
import {useDispatch} from "react-redux";
import {selectedPlace} from "../../actions/searchActions";

const PlaceList=function (props) {
    const dispatch=useDispatch()

    const handleClick=function (id) {
        console.log('ciao '+id)
    }
    return(
        <ListGroup>
        {props.places.map(item=>{
            return (<ListGroup.Item variant="flush" onClick={handleClick(item['place_id'])}>{item['formatted_address']}</ListGroup.Item>)
        })}
        </ListGroup>
    )
}

export default PlaceList

I want the onClick to be fired just when the list item is clicked. Any Idea on how to solve?

kind user
  • 40,029
  • 7
  • 67
  • 77
gloria00
  • 265
  • 2
  • 15
  • As with the many duplicates, don’t call the function at binding. The binding site should evaluate to a function, and this returned function is the callback. Having the handleClick (call it handleClickCreator) return a closure is one method, as is creating a simple wrapping lambda. Behavior is discussed in https://reactjs.org/docs/handling-events.html as well. – user2864740 Sep 26 '20 at 16:42
  • https://stackoverflow.com/q/34226076/2864740 – user2864740 Sep 26 '20 at 16:45

2 Answers2

0

onClick functions should be called like this!

import { ListGroup } from "react-bootstrap";
import { useDispatch } from "react-redux";
import { selectedPlace } from "../../actions/searchActions";

const PlaceList = (props) => {
  const dispatch = useDispatch();

  const handleClick = (id) => {
    console.log('ciao ' + id)
  }
  return (
    <ListGroup>
      {
        props.places.map(item => {
          return (<ListGroup.Item variant="flush" onClick={() => handleClick(item['place_id'])}>{item['formatted_address']}</ListGroup.Item>)
        })
      }
    </ListGroup>
  )
}

export default PlaceList
Veno
  • 433
  • 2
  • 14
0

Your onClick should be calling the function like this:

import { ListGroup } from 'react-bootstrap';
import { useDispatch } from 'react-redux';
import { selectedPlace } from '../../actions/searchActions';

export default (props) => {
  const dispatch = useDispatch();

  const handleClick = (id) => {
    console.log('ciao ' + id);
  };

  return (
    <ListGroup>
      {props.places.map((item) => (
        <ListGroup.Item variant="flush" onClick={() => handleClick(item['place_id'])}>
          {item['formatted_address']}
        </ListGroup.Item>
      ))}
    </ListGroup>
  );
};
Angel Zlatanov
  • 288
  • 1
  • 5