Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map iterator undefined React.JS

I'm trying to render a list, but when I try and map over the list I can not access each individual element, because I ReferenceError saying that 'e' is undefined. Am I writing this correctly?

  render() {
    return (
      <div>
         {console.log(Object.keys(this.props.emojis))} --> Returns the correct list
          Object.keys(this.props.emojis).map(e => (
              {console.log("EMOJI: ",e)}
              <Emoji emote={e} />
          ))
      </div>
    )
 }
like image 326
Darkzuh Avatar asked Feb 03 '17 07:02

Darkzuh


2 Answers

Write it like this, it will work:

render() {
    return (
      <div>
           {            
              Object.keys(this.props.emojis).map((e,i) => {
                 console.log("EMOJI: ",e);
                 return <Emoji key={i} emote={e}/>
              })
            }
      </div>
    )
 }

Changes:

  • You are already inside a map function, so no need to use {} for console.log.

  • You are using () with map function and inside () you are using 2 statement, that is not allowed with (), if you want to do some calculation always use {}, and return something inside it.

Suggestion: Always assign key whenever creating the ui items dynamically.

Let me know if you need any help.

like image 118
Mayank Shukla Avatar answered Nov 03 '22 00:11

Mayank Shukla


See if this work for you.

logging(e) {
    console.log("EMOJI: ", e);
}

render() {
   return (
     <div>
       Object.keys(this.props.emojis).map(e => (    
         this.logging(e);
         <Emoji emote={e} />
       ))
     </div>
   )
}
like image 26
PSo Avatar answered Nov 03 '22 01:11

PSo