Search code examples
javascriptreactjsparametersmap-function

Passing a function with parameters to mapped elements


The function changeVideo is defined like this,

  changeVideo(url) {
    alert(url)
  }

UI'm trying to pass it to several mapped images. Here is the function that receives changeVideo and maps it to said images. videos is an object. The url ingested by changeVideo is a property of the videos object.

function videoList(videos, changeVideo) {
  return Object.keys(videos).map((key) => {
    return (
      <div>
        <img
          onClick={() => this.changeVideo(videos[key].url)}
        />
      </div>
    );
  });
}

Finally, here is where I call the videosList function, and pass changeVideo to it.

 <div className="videoList">
      {videoList(this.state.videos, this.changeVideo)}
</div>

Somewhere in the process, I'm passing changeVideo incorrectly. Thanks for looking!


Solution

  • this inside videoList would not have a changeVideo property, but since you are already passing it as a function, use changeVideo directly:

    this.changeVideo(videos[key].url changes to changeVideo(videos[key].url