Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  50] [ 7]  / answers: 1 / hits: 84406  / 9 Years ago, fri, december 11, 2015, 12:00:00

I have a component that I have created:



class Create extends Component {
constructor(props) {
super(props);
}

render() {
var playlistDOM = this.renderPlaylists(this.props.playlists);
return (
<div>
{playlistDOM}
</div>
)
}

activatePlaylist(playlistId) {
debugger;
}

renderPlaylists(playlists) {
return playlists.map(playlist => {
return <div key={playlist.playlist_id} onClick={this.activatePlaylist(playlist.playlist_id)}>{playlist.playlist_name}</div>
});
}
}

function mapStateToProps(state) {
return {
playlists: state.playlists
}
}

export default connect(mapStateToProps)(Create);


When I render this page, activatePlaylist is called for each playlist in my map. If I bind activatePlaylist like:



activatePlaylist.bind(this, playlist.playlist_id)


I can also use an anonymous function:



onClick={() => this.activatePlaylist(playlist.playlist_id)}


then it works as expected. Why does this happen?


More From » reactjs

 Answers
4

You need pass to onClick reference to function, when you do like this activatePlaylist( .. ) you call function and pass to onClick value that returned from activatePlaylist. You can use one of these three options:



1. using .bind



activatePlaylist.bind(this, playlist.playlist_id)


2. using arrow function



onClick={ () => this.activatePlaylist(playlist.playlist_id) }


3. or return function from activatePlaylist



activatePlaylist(playlistId) {
return function () {
// you code
}
}

[#64098] Wednesday, December 9, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katia

Total Points: 570
Total Questions: 101
Total Answers: 85

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;