Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does react render an array of strings into an HTML element?

I would like to understand why does this happen, just for education purposes.

So I have an array of strings:

const wordArr = ["h", "o", "l","a", " ", "m", "u", "n", "d", "o"];

If you pass this array into an JSX

return <p>{word}</p>

Then the output will be like this:

<p>hola mundo</p>

Why does React interpret this array as a single sentence. I just want know why it happens, what's the mechanism behind it? This could be helpful when you have an array of words, and HTML elements where you can manipulate the HTML elements by passing a class/style.

Honestly, I didn't know you could do this and I have been using recently but I really don't know why it's doing that. It would be nice to know why does this happen. Thank you in advance for sharing your knowledge.

like image 528
medev21 Avatar asked Nov 06 '22 01:11

medev21


1 Answers

Jsx interpret your values inside curly braces {} and render them inside components, this is the expected behavirour.

the common question then is how we render a list(array)?

we loop over it and render each item in different jsx element

const staticItems = [ 'hello', 'world' ];

function SomeComponent(props){

  return (
    <div>
      { items.map(item => (<span key={item}> {item} </span>)) }
    </div>
  );
}

Why the key?

Because react need an id for each item that it use internally for the next future renders, so if the key didn't change react don't re-render the element again and use the last rendered version.

How to render the array ['h','e','l','l','o'] as "hello"?

well, you have to convert it to string first if what you want was the concatenated word "hello"

<div>
  { arrayOfChars.join("") }
</div>

You can read more about lists rendering at React Doc

But why React did allow putting an array in JSX?

I'm not that nerd expert, but as far as I know, it doesn't care, it just has a value, and it interprets it(jsx is just a representational syntax over underlying real JS functions at the end), but it has a unique behaviour for arrays of course, and that it convert each item in the array to a string and then render the items(their string conversion result) along each other

like image 114
Mhd Louay Al-osh Avatar answered Nov 15 '22 06:11

Mhd Louay Al-osh