DEV Community

Cover image for This is why you can't return adjacent JSX elements.

This is why you can't return adjacent JSX elements.

Tushar Kashyap on September 05, 2020

I've been using React for quite some time now and it's an amazing tool to write maintainable applications pretty fast. But I remember when I starte...
Collapse
 
hisham profile image
Hisham Mubarak

I've had to use the <> </> a few times, and also returned elements inside arrays a few times too, after this adjacent JSX error came up. Finally I understood why is the way is it. Thanks for the nice article.

Collapse
 
tusharkashyap63 profile image
Tushar Kashyap

Glad I could help.

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan

Nice explanation. I have also written a similar article some time back with additional details which you can check out here

Collapse
 
tusharkashyap63 profile image
Tushar Kashyap • Edited

I checked it out, good work.
Check out his article to see more about how React.createElement works.

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan

Thank you so much!

Collapse
 
itsjzt profile image
Saurabh Sharma • Edited

You can always return

function returnSelf(a, b) {
  return [
    a,
    b
  ]
}
Collapse
 
tusharkashyap63 profile image
Tushar Kashyap

Yes I said we can return arrays

Collapse
 
thehanimo profile image
Hani • Edited

What if React could automatically add <>, </> around these adjacent JSX elements?

Collapse
 
tusharkashyap63 profile image
Tushar Kashyap • Edited

But your program will never reach that stage when React can do anything. Wrong syntax will break your program in the first place. Please abide by the rules of JavaScript as React is just JavaScript.

Collapse
 
thehanimo profile image
Hani

I mean, while compiling, can’t React intelligently figure it out and add a parent block? I know it doesn’t do that now but it is quite possible isn’t it?

Thread Thread
 
Sloan, the sloth mascot
Comment deleted
 
devhammed profile image
Hammed Oyedele

That is asking too much 😅

React is just a library.

Collapse
 
thebuildguy profile image
Tulsi Prasad

Great writeup!

Collapse
 
tusharkashyap63 profile image
Tushar Kashyap

Thank you so much :)

Collapse
 
wannabehexagon profile image
ItsThatHexagonGuy

You get that error because you can only return one thing at any given time. That error translates to "do something so you will only return one thing".

Collapse
 
tusharkashyap63 profile image
Tushar Kashyap • Edited

I know it asks you to return one element. In this article I'm trying to explain WHY does it want you to return one element.

Collapse
 
paras594 profile image
Paras 🧙‍♂️

Great post and explanation !!

Collapse
 
tusharkashyap63 profile image
Tushar Kashyap

Thank you, Paras :)