0

I'm developing an application using React JS and JSX. It is kind of On the Job Training. One thing I noticed is, I get the same result for two different types of code. I would like to understand more about this. Can someone explain this, please?

Code Block one

{
    this.state.entities.map((entity, index) => {
        return <Link key={index} to={{ pathname: '/details/'}}>{entity.main_question}</Link>
    })
}

Code Block two

{
    this.state.entities.map((entity, index) => (
        <Link key={index} to={{ pathname: '/details/' }}>{entity.main_question}</Link>
    ))
}
Jacob Nelson
  • 2,370
  • 23
  • 35
  • Because in essence it's the same: the `()` within the map returns the component, whereas the `{}` allows you to add additional code before you return the component. – DavidP Jun 06 '19 at 06:28
  • It's because you can *implicitly* return values with arrow functions, see @BoyWithSilverWings comment link – Jayce444 Jun 06 '19 at 06:30

3 Answers3

0

The map function of javascript loops through array of objects and return the value for each iteration.

Example: In normal JS,

const arr=[1,2,3,4,5];
const squared=arr.map(function(value){return value*value})//squared=[1,4,9,16,25]

Now in arrow functions you can write the callback as follows

const squared=arr.map((value)=>value*value)//This is same as return value*value in the function body.
Thakur Karthik
  • 3,034
  • 3
  • 15
  • 24
0

about code block one :

when you use => {} curly braces you have to use return

{
    array.map((item, index) => {
        return something
    })
}

code block two :

when you use => () it will direct return the expression or component , no need to add return here

 {
        array.map((item, index) => ( something ))
 }

now question arrives in your mind when to use which one :

generally when you have some if conditions use code block 1 :

{
        array.map((item, index) => {
            if(some_codition_here){
              return something;
            }else{
              return something_else;
            }
        })
}

if there is no conditions you can use code block 2 .

Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71
0

The answer is there in the code itself

In this case, you are using = {} So you have to write the keyword return

{
    this.state.entities.map((entity, index) => {
        return <Link key={index} to={{ pathname: '/details/'}}>{entity.main_question}</Link>
    })
}

In this case, you are using = () , So you don't have to use return

{
    this.state.entities.map((entity, index) => (
        <Link key={index} to={{ pathname: '/details/' }}>{entity.main_question}</Link>
    ))
}

Because it is a new feature in ES6, It is basically like writing in a single line without

Thanveer Shah
  • 3,250
  • 2
  • 15
  • 31