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

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -