I am trying to set a video in my app as "Featured" when a user clicks on an item. I have an action creator that does a simple console.log() when called, and for testing I call it w/ componentDidMount()
, and it works fine. I have a separate component for the VideoItem, and I'm trying to pass down the action creator, but I get an error: TypeError: Cannot read property 'props' of undefined
. I tried to add .bind(this)
to the end of the action I was passing down, but it didn't make a difference.
If the action creator works when I call it at componentDidMount
, why can't I pass it to the child component? Here's my Video and VideoItem component:
// Video.js
import React, { Component } from 'react'
import VideoItem from './VideoItem'
class Videos extends Component {
componentDidMount() {
this.props.actions.getVideos()
// This function works, but getting error
// when passing to VideoItem component
this.props.actions.setFeaturedVideo()
}
constructor(props) {
super(props);
}
render() {
if(this.props.videos.length == 0){
return <p>Loading....</p>
}
return (
<div className="container">
<ul className="row">
{this.props.videos.map(function(result) {
return (
<VideoItem
key={result.position}
setFeaturedVideo={this.props.setFeaturedVideo}
video={result}
/>
)
})}
</ul>
</div>
)
}
}
export default Videos
// VideoItem.js
import React, { Component } from 'react'
class VideoItem extends Component {
constructor(props) {
super(props);
}
render() {
return (
<li className="col m6" onClick={this.props.setFeaturedVideo()}>
{this.props.video.title}
</li>
)
}
}
export default VideoItem
Missed that this inside a map function. Since you are using map, the "this" belongs to the map function. You need to assign this to a variable before the map function and use that instead.
render() {
var _that = this;
if(this.props.videos.length == 0){
return <p>Loading....</p>
}
return (
<div className="container">
<ul className="row">
{this.props.videos.map(function(result) {
return (
<VideoIte
key={result.position}
setFeaturedVideo={_that.props.actions.setFeaturedVideo}
video={result}
/>
)
})}
</ul>
</div>
)
}