Can I wrap multi-line JSX expressions in an element other than a <div>?

Question

Can I wrap multi-line JSX expressions in an element other than a <div>?

Answer

JSX expressions can be wrapped in an element other than a <div> element to be sure that the first opening tag and final closing tag of a JSX expression belong to the same element.

This element can be an HTML element where the nesting is valid according to HTML5 specifications (see MDN documentation to check for permitted content in a specific element) or, this element can be custom components that have child components or other HTML elements nested inside.

8 Likes

dear @aubsrey!

if your goal is only wrapping, you can also use the short syntax for this purpose.

looks like this:
<>
<p>Hello there</p>
<p>Have a nice day!</p>
</>

it’s on the official site of React, here you can read about it

I hope it helps! :slightly_smiling_face:

84 Likes

update: you can also use Fragments.
Fragments let you group a list of children without adding extra nodes to the DOM.

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}

Here is the article about it

48 Likes

I like that and now that there’s a short syntax it works even better

1 Like

How old is this lesson about jsx? Looks like it was written before React introduced fragment. Will it be updated in the near future?

10 Likes

It looks like React had introduced Fragment, but probably hadn’t introduced the short syntax yet. I would definitely encourage codecademy to update this lesson to use the shorthand Fragment syntax instead of adding another element in the DOM hierarchy.

7 Likes

Oh, this is really clever!

Absolutely :sparkling_heart: it!

thank you for the tip this is very good

Ohh Thanks for the tip, It has made my code easier