Home > Net >  How do I use the append ( =) operator for JSX?
How do I use the append ( =) operator for JSX?

Time:11-11

I'm trying to use the append ( =) operator for a JSX expression:

let j = "";
for (let i in [1,2,3]) {
  j  = <span>{i}</span>;
}

But it unexpectedly renders as three strings, instead of HTML:

[object Object][object Object][object Object]

CodePudding user response:

The append operator is not supported in JSX. Use Array.map() instead:

[1,2,3].map((i) =>
  <span>{i}</span>
);

CodePudding user response:

If you want to print html into the JSX coming from any method or coming dynamically then you could do -

let j = "";
for (let i in [1,2,3]) {
  j  = `<span>${i}</span>`;
}

And in JSX,

<div dangerouslySetInnerHTML={{__html: j}} />

This will render 123 into your UI.

Note - Please research more about dangerouslySetInnerHTML before using it.

  • Related