loko
loko

Reputation: 17

How to concatenate React objects without JSX

How can I concatenate two React objects(React.createElement()) without JSX ?

Goal

My goal is to render message, the message should contain the user full name in bold.

Problem

The problem is that when I concatenate the react objects I am getting the message content and instead of the full name there is [object Object] in the string.

Code

var firstName = React.createElement("b", {}, this.state.User["FirstName"])
var lastName = React.createElement("b", {}, this.state.User["LastName"])
var message = "Hello " + firstName + " " +  lastName
message += " You can edit your profile in the Users Table"
return React.createElement("p", {}, message)

Upvotes: 0

Views: 1110

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281864

React.createElement returns you an Object of the component instance, you cannot directly concat it with a string. you instead can pass them to createElement as an array of children elements

 var firstName = React.createElement("b", {},  this.state.User["FirstName"])
 var lastName = React.createElement("b", {}, this.state.User["LastName"])
 const message = ["Hello ", firstName, " ", lastName, " You can edit your profile in the Users Table"]
 return React.createElement("p", {}, message);

Working demo

class App extends React.Component {
   render() {
      var firstName = React.createElement("b", {},  "Stack")
      var lastName = React.createElement("b", {}, "Overflow")
      return React.createElement("p", {}, ["Hello ", firstName, " ", lastName, " You can edit your profile in the Users Table"]);
   }
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"/>

Upvotes: 1

徐銘谷
徐銘谷

Reputation: 361

You should concatenate them using array as follows:

var firstName = React.createElement("b", {}, this.state.User["FirstName"])
var lastName = React.createElement("b", {}, this.state.User["LastName"])
var message = ["Hello ", firstName, " ", lastName]
message.push(" You can edit your profile in the Users Table")
return React.createElement("p", {}, message)

Upvotes: 2

Related Questions