0

I don't understand why this ReactJS code is written like it is. I would like someone to talk me through it bit by bit.

I understand ternary operators and If/Else in JSX and React but not this. Specifically the

if (i > 2) return return child })}

I don't see how that code works (but it does). I mean return then return?

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

function Parent() {

    return (      

       <Head >
           <span>1</span>
           <span>2</span>
           <span>3</span>
           <span>4</span>
           <span>5</span>
           <span>6</span>
           <span>7</span>
       </Head> 

    )
}

function Head({children}){

return (
<div>{React.Children.map(children, (child, i) => {
        if (i > 2) return
        return child
                })}
    </div>

        )
    }

ReactDOM.render(<Parent />, document.getElementById('root'));

What I'm doing is trying to learn about the children props. I want to display the first 3 children (which it does) but I don't understand the

map(children, (child, i) => { if (i > 2) return
return child
})}

NightTom
  • 294
  • 4
  • 22
  • 3
    if `i > 2` return nothing, else if `i` is less than 2 return child. can be written like `if (i > 2) {return} else { return child}` – Junius L. May 09 '19 at 15:32
  • 3
    To elaborate on the linked duplicate - your code is actually being interpreted as `if (i > 2) return; return child;` due to automatic semicolon insertion. I'd recommend always using braces around `if`/`else` blocks to avoid this kind of confusion. I'd also recommend using semicolons, but I understand that's a matter of taste ;) – Joe Clay May 09 '19 at 15:33
  • All of you have answered my question. I can only mark Jake's as an answer (which it is) but I've marked both of yours as useful. – NightTom May 10 '19 at 09:09

1 Answers1

1

You are iterating over an array of "children." "child" represents the current item in the array while "i" represents the index of that element. Since arrays are zero based the first statement reads if "i" has hit the 3rd iteration ( 0, 1 , 2) then return from the map function and don't execute the next line. Otherwise return the "child".

Jake
  • 676
  • 6
  • 20