function - Cannot read property 'props' of undefined (React) -


i've got react component renders content conditionally, it's bit verbose , repetitive. i've tried wrap repeated code in function call later (the output dependent on whatever argument give function) isn't working.

original (verbose) solution:

render() {    const userid = parseint(this.props.params.userid)   const {posts} = this.props    if(userid) {      const postsforuser = posts.filter( post => post.userid === userid )      return (         <div>            {postsforuser.map( post =>               <post {...this.props} post={post} key={post.id} />            )}         </div>      )   }   else {      return (         <div>            {this.props.posts.map( post =>               <post {...this.props} post={post} key={post.id} />            )}         </div>      )   }  } // end render() 

(unsuccessful) attempt trim down

render() {    const userid = parseint(this.props.params.userid)    function renderpostlist(postsinput) {      return (         <div>            {postsinput.map( post =>               <post {...this.props} post={post} key={post.id} />            )}         </div>      )   }    if (userid) {      const postsforuser = this.props.posts.filter( post => post.userid === userid )      return renderpostlist(postsforuser)   }   else {      return renderpostlist(this.props.posts)   }  } 

i receive error: cannot read property 'props' of undefined

i know problem function's scope, , how this referencing wrong (or nothing, in case) struggle head around how solve this. if can explain what's going wrong in instance, appreciate it.

you should able moving renderpostlist method out of render method , class level.

renderpostlist = (postsinput) => (   <div>     {postsinput.map( post =>       <post {...this.props} post={post} key={post.id} />               )}   </div> )  render() {    const userid = parseint(this.props.params.userid)    if (userid) {      const postsforuser = this.props.posts.filter( post => post.userid === userid )      return this.renderpostlist(postsforuser)   }   else {      return this.renderpostlist(this.props.posts)   }  } 

Comments

Popular posts from this blog

.net - Bulk insert via Dapper is slower than inserting rows one-by-one -

shared memory - gstreamer shmsrc and shmsink with h264 data -

java - is not an enclosing class / new Intent Cannot Resolve Constructor -