The Many Ways to Return JSX

JSX is a great tool because it has so much flexibility. There are many ways to achieve the same thing. For this reason, it can be confusing for new developers when they see different tactics for defining and returning JSX elements.

Let's take a look at the different ways we can return JSX elements.

In React, you may see different ways of returning JSX templates. It's good to see them all so that you know what is valid and what isn't.

We can return the element right after a return like we've done in previous examples:

jsx
// return the element directly
return <div>hello</div>;

By wrapping our entire JSX return with parentheses, we can make a multi-line JSX return.

jsx
// return with a wrapper ()
return (
  <div>what's up</div>
);

Note: The big thing to note here is that the return must always have one parent element. Here's a comparison of valid and not valid JSX returns:

jsx
// 🚫 NOT VALID: 2 top-level elements
return (
  <div>what's up</div>
  <div>what's up</div>
);

// βœ… VALID: must have 1 top-level (parent) element
return (
  <div>
    <div>what's up</div>
    <div>what's up</div>
  </div>
);

Just like we were able to return an element directly, we are able to return an element out of a ternary statement.

This means we can quickly check if there is a true/false value and then return one of two elements.

jsx
// return out of a javascript ternary
return isActive ? <div>i am active!</div> : <div>inactive</div>;

We can also use a larger ternary statement with parentheses:

jsx
// return out of a larger ternary
return isActive ? (
  <div>
    <h2>bunch of stuff</h2>
    <p>look im a paragraph</p>
  </div>
) : (
  <div>inactive</div>
);

Notice that you can return a JSX element directly or you can have it wrapped with () for larger blocks of code.

Another useful pattern is to return an element early in your component. This way, we can stop executing the component if a true statement is found. Notice how we return a <LoggedIn /> component if the user is logged in.

jsx
function Nav() {
  const isLoggedIn = true;

  // user is logged in. return this component and stop executing
  if (isLoggedIn) return <LoggedIn />;

  // user wasnt logged in. show this stuff
  return (
    <div>you need an account</div>
  );
}

JSX is very flexible. It's important to recognize all the different ways we can return elements since you'll see them in code across the web. You'll also be able to use each one based on your use-case in your own code.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)