⚠️ This lesson is retired and might contain outdated information.

Display Output in React with a Component's render Method

Joe Maddalone
InstructorJoe Maddalone
Share this video with your friends

Social Share Links

Send Tweet
Published 10 years ago
Updated 2 years ago

The render method is where the magic happens in your React components to display output to the screen. This lesson explains how to structure your JSX in a React component.

[00:00] The render method of our React component is only allowed to return a single node. To illustrate that, right here after the H1, I'm going to create a second node. It's a bold tag with an inner HTML of bold. We can see we do in fact get an error here. "Adjacent JSX elements must be wrapped in an enclosing tag."

[00:19] The reason this doesn't work is it's the equivalent of trying to return a function followed by another function. That function is React.createElement. It'd be like trying to return React.createElement followed by React.createElement, and that's not going to translate well to JavaScript.

[00:36] The way that we solved this is by wrapping our nodes in a parent node. I'm just going to create a div here. I'm going to wrap these guys, our H1 and our <bold> tag, in that div.

[00:48] Let me just clean this up a little bit, save that, and we can see on the right everything is working as expected.

[00:55] You'll notice I am wrapping my JSX in parentheses. I can go ahead and get rid of those. Everything will work fine if I bring the first line of our JSX up to the same line as the return statement.

[01:06] That's going to work just fine, but as soon as I put it onto the next line, it is in fact going to break. I just as a preference, not a requirement, wrap my JSX in parentheses just so that I can utilize all the white space.

themathmagician
themathmagician
~ 6 years ago

where can I find the example code?

Jean-Denis Vauguet
Jean-Denis Vauguet
~ 6 years ago

As of React 16 one is able to return more than one element: https://pawelgrzybek.com/return-multiple-elements-from-a-component-with-react-16/

Markdown supported.
Become a member to join the discussionEnroll Today