React - how to render adjacent JSX elements

arikaturika

Arika O

Posted on July 9, 2020

React - how to render adjacent JSX elements

If you've been using React you must know already that we are only allowed to render one JSX (that code you find in the return statement and looks like HTML but it's not) element at a time. Trying to break this rule will result into an error like the one we can see bellow:

Alt Text

SyntaxError: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

This can be easily fixed by wrapping our two elements into a div, which would be treated by React as the single element it needs to behave correctly..

Alt Text

Another way to avoid this problem is by transforming the code in the return block into an array of elements. It looks weird and I never use this approach but it's good to know it's out there (note that you still need to provide a unique key for each element so you don't get an error):

Alt Text

We could also wrap all our elements into a React.Fragment. It lets us group as many components as we want, without adding an extra node to the DOM. It behaves similar to a div and I don't think it has any real advantages over divs, unless we use it in really large applications where not creating extra nodes would help performance. You can write a React.Fragment in two ways: <React.Fragment></React.Fragment> or <></>.

Alt Text

Alt Text

Another solution to our problem would be a HOC (higher order component). We can create one with the single purpose of wrapping our JSX elements every time we need to (since it's a component as any other, it's reusable and we can include it in our code as many times as we want).

Alt Text

We create a HOC which does nothing than rendering its children (which in our case are all the JSX elements we need to display).

Every React component has a special (default) prop called children and the children represent everything we want to put in between the opening and the closing tags of a component.

Image source: Goran Ivos/ @goran_ivos on Unsplash

πŸ’– πŸ’ͺ πŸ™… 🚩
arikaturika
Arika O

Posted on July 9, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related