One question regarding React

Hello,

I am having one question from this challenge:

In render(), it asks to write a map() to generate “li” from user input, where I tried it like this:

const items = this.state.toDoList.map(v => "<li>" + v + "</li>");

but this doesn’t work as a list item as I expected.
It did not get transformed by html, but it is displayed like this instead:
<li>apple</li><li>banana</li>

The correct answer is this:

const items = this.state.toDoList.map(v => <li>{v}</li>); 

The correct answer produces the results wanted like this:

  • apple
  • banana
  • I wonder why mine doesn’t work?

    And also, for the correct answer, why it requires { } to wrap around “v” inside map()?
    Shouldn’t curly braces only be required in return() block?
    What should be the correct concept behind this?

    Thank you.

    This

    "<li>" + v + "</li>"
    

    will return a string.

    This

    <li>{v}</li>
    

    will return JSX.

    Remember that JSX isn’t really JS. It is a meta language that the babel preprocessor will magically and invisibly (to you) convert into JS and HTML to inject into you app.

    The curly braces are necessary because you need to tell babel, “OK, you’re processing some JSX right now, but I’m going to inject a little JS here.”

    2 Likes

    One of the goals of the challenge is to go through the toDoList and tranform every item in that list to a list item written in a syntax kind of similar to HTML (It’s called JSX)

    If you take a closer look at the prewritten code whatever the value of items const is would show up within the <ul> element. i.e {} is telling to react that you have to evaluate the variable within {}.

    But what is the value of the items variable?
    The value in your case is two strings stuck together. Each of the string has an

  • element with the value of v within it.
    The value in the solution is not a string. It’s JSX code. There is no sign of + and nothing similar to typical strings. And that’s what’s needed some JSX code to reside within <ul> tags.

    Regarding the {} for the v, since we’re using HTML syntax (Template syntax) we need to use {} to tell the react to go and evaluate whatever you see in place v.

    Hope this helps, and let us know if it didn’t.
    Good Luck! :call_me_hand:

  • 1 Like

    Thank you for the answers!
    One thing I am still not so clear is { }.
    How can we tell what is considered JSX for the babel processor and what is considered just Javascript?

    Everything in your JS file is JS, unless…

    unless it is envlosed in some JSX, like a JSX tag like <li>...</li> or <MyComponent>...</MyComponent>. Anything in there isn’t in JS land, it’s in JSX land. In order to inject JS in there, you need the curly braces.

    2 Likes

    Just keep doing it. It’s weird at first but with use it makes more sense.

    1 Like

    I see.
    Yeah, it’s pretty confusing.
    I will keep it going.
    Thank you! :slight_smile:

    1 Like