React Starter: The Many Ways to Return JSX
Publikováno: 13.6.2019
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 de...
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.
Returning the element directly
We can return the element right after a return
like we've done in previous examples:
// return the element directly
return <div>hello</div>;
Returning with a wrapper ()
By wrapping our entire JSX return with parentheses, we can make a multi-line JSX return.
// 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:
// 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>
);
Returning out of a ternary statement
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.
// 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:
// 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.
Returning early
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.
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>
);
}
Conclusion
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.