Angela Yu Angela Yu -3 years ago 165
HTML Question

How to render a JSX that is inside a variable

I am doing an if/else statement to set the contents of the JSX element called 'signupMessage'. I later render the contents of 'signupMessage'.

render() {
let signupMessage;
if (this.state.signUpForNewsletter === true) {
signupMessage = <h1>Thank you</h1>;
} else if (this.state.signUpForNewsletter === false) {
signupMessage = <h1>Be the first</h1> + <h1>to see the latest!</h1>;
<section className="sign-up">

In the 'else if' block, I need two h1 tags in order to have control over exactly which words appear on a line, even on different devices, as per specs.

Right now, this outputs as "[object Object][object Object]". How do I get the JSX to render as h1 tags??

Answer Source

In your code, this line:

<h1>Be the first</h1> + <h1>to see the latest!</h1>

gets transpiled to:

React.createElement("h1", null, "Be the first") +
React.createElement("h1", null, "to see the latest!");

React.createElement returns an object, and object + object in JS results in:

"[object Object][object Object]"

which is why you are seeing that output.

How to fix this

Wrap the two <h1>s in a <div>:

signupMessage = <div><h1>Be the first</h1><h1>to see the latest!</h1></div>;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download