< Previous: How to Write if/else Conditional Statements in JSX   Next: Handling Events with JSX: onClick >

Using JSX to Render Several Elements at Once

Our current code isn't very exciting, but I hope you can feel you're learning things. To make things more interesting, let's print both a name and a country for our fictional person.

This is easy to do with the Chance library we already added, but first please remove the ternary expression if you added it, going back to a very basic render() method like this:

src/pages/Detail.js

return <p>Hello, {chance.first()}!</p>;

OK, nice and easy again. Adding a random country name using Chance is done like this:

chance.country({ full: true });

That will return "Australia" or other country names, ready to use, so you might think we could modify our render() method to look something like this:

render() {
    return <p>Hello, {chance.first()}.</p>
        <p>You're from {chance.country({ full: true })}.</p>;
}

But if you try that you'll find that React refuses to load your page. Inside your browser's message console you'll see a wall of red error messages telling you that your JSX is invalid. So what went wrong?

Well, as with ternary expressions this is another instance where you need to "look behind the curtain" of JSX to see what's going on: your render() method gets to return one and only one value, and each of those <p> elements gets converted into code when your app is built. So, when the app gets built, having two <p> elements means you're trying to return two values, which isn't possible.

There is a solution, and it's an easy one: wrap those two <p> elements inside another element, e.g. <div> element. If you do that, JSX can clearly see the start and end of a single return value, and everything works again.

So, again, here's the bad code:

render() {
    return <p>Hello, {chance.first()}.</p>
    <p>You're from {chance.country({ full: true })}.</p>;
}

And here's the fixed code that wraps both those <p> elements inside a single <div>:

src/pages/Detail.js

render() {
    return (<div>
        <p>Hello, {chance.first()}.</p>
        <p>You're from {chance.country({ full: true })}.</p>
    </div>);
}

It doesn't matter how many child elements (or grandchild elements, great-grandchild elements, etc) that <div> has, as long as there is only one element being returned.

Returning more than one JSX element from your render() method is not possible and will output a great many error messages.

Buy the book for $10

Get the complete, unabridged Hacking with React e-book and take your learning to the next level - includes a 45-day no questions asked money back guarantee!

If this was helpful, please take a moment to tell others about Hacking with React by tweeting about it!

< Previous: How to Write if/else Conditional Statements in JSX   Next: Handling Events with JSX: onClick >

Copyright ©2016 Paul Hudson. Follow me: @twostraws.