2

I'm working inside a stateless function controller in React. I'm trying to do a console.log inside a map that is inside a return statement. This works:

{options.map(o => (
   {console.log(o)}
))}

And this works:

return (
   <>
      //more html/jsx code
      {console.log("test")}
      //more html/jsx code
   </>
)

But how to log inside a map that is inside a return statement? like so:

return (
   //more html/jsx code
   {options.map(o => (
      <>
         {console.log(o)} //doesn't compile
         console.log(o) //doesn't work -> written in DOM
      </>
   ))}
   //more html/jsx code
)

Anyone have an idea if this is possibly at all. I find many answers articles/questions where they do 1 of the 2. Or in a map or in a return statement. Can't seem to find an answer that is both in a return statement and a map. I, ofcourse, only use console.log for testing purposes

control-panel
  • 255
  • 6
  • 17

2 Answers2

3

You are still able to console inside the map function. But you should put console.log out of return JSX element.

const array = ['test', 'item2', 'item3'];
array.map(item => {
  console.log(item) // put your console here.
  return (
    <>{item}</>
  )
})

This will be duplicated with this question

ArtDev
  • 46
  • 4
1

You are making an implicit return in this map here and returning multiple nodes at the same level. They should always be contained into one single node, so this:

return (
   {options.map(o => (
      {console.log(o)} //doesn't compile
      {console.log(o)} //doesn't work -> writes in DOM
   ))}
)

Should be changed to this: (notice the use of React.Fragment or <>)

return (
   {options.map(o => (
      <>
        {console.log(o)}
        {console.log(o)}
      </>
   ))}
)

Which makes a single node out of the output and lets react render properly.

Anyway, I don't recommend retuning console.log anytime in React, you could instead do the console logs and return a null so React knows that there's nothing to render in there.

return (
   {options.map(o => {
      console.log(o)
      return null;
   })}
)
Cristian
  • 56
  • 2
  • There is content in my return statement, i just filtered it out to give the essence of the problem. I will make it more clear. – control-panel Feb 19 '20 at 13:44