irregular irregular -3 years ago 88
React JSX Question

How can a span element be appended to an array of Strings, .join(","), and rendered?

I have

var pos = ["a","b"]
pos.unshift(<span className="common">Common Word</span>)
var parts_of_speech = pos.join(', ')


Rendering
{pos}
prints
Common Word
properly and I can style the css class. Printing
{parts_of_speech}
results in
[object Object]
instead of
Common Word
being printed.

What can be done to make this do what I would expect or is this the wrong way to go about doing this?

Answer Source

When you say <span className="common">Common Word</span> in JSX, you are not dealing with a span element. It is actually just a JavaScript function call:

React.createElement(
  "span",
  { className: "common" },
  "Common Word"
);

You can use Babel to get the result above.

So you are getting the result of joining the result of a function with a string.

Your code translate to the following with Babel:

var pos = ["a", "b"];
pos.unshift(React.createElement(
  "span",
  { className: "common" },
  "Common Word"
));
var parts_of_speech = pos.join(', ');

So if React.createElement returns some object, it should have a toString() method that outputs [object Object].

Like this example:

"use strict";

var pos = ["a", "b"];
pos.unshift((function() { return {}; })());
var parts_of_speech = pos.join(', ');

console.log(parts_of_speech)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download