Autoplay

    Display Output in React with a Component's render Method

    Joe MaddaloneJoe Maddalone

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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 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.

    Discuss

    Discuss