0

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) 
3
  • have u tried to access the text by using props? I guess it's the only way Commented May 14, 2020 at 10:01
  • Does this answer your question? how to render multiple children without JSX Commented May 14, 2020 at 10:02
  • How can I do this with props ? Commented May 14, 2020 at 10:05

2 Answers 2

2

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) 
Sign up to request clarification or add additional context in comments.

Comments

1

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"/>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.