In React we're working with JSX. JSX is that code you return in your Components which in the end will be rendered to the Real Dom By React. That what JSX is and we use it all the time. BUT jsx has certain limitations , specifically there is one limitation which we all has faced. if we have adjacent root level JSX elements like in this example we'll get an error.
return (
<h2>Hi There!</h2>
<p>This does not work</p>
);
Note: You can't return more than one "root" JSX element (you also can'ts store more than one "root" JSX element in a variable).
So What is the Best Solution for that ?
There are 3 solutions to this problem:
1_React Fargments: This is of course the best solution and this will always work.
import React, { Fragment} from 'react';
return (
<Fragment>
<h2>Hi There!</h2>
<p>This does not work</p>
</Fragment>
);
2_React tag You can also use this shortcut , but this depends on your project setup ,because your build workflow needs to support this. The first syntax (1) will always work.
import React from 'react';
return (
<>
<h2>Hi There!</h2>
<p>This does not work</p>
</>
);
3_Creating a Wrapper Component we have to create a empty component named wrapper for example and after that we can wrap our JSX elements by
wrapper.js
const Wrapper = (props) => {
return props.children;
}
export default Wrapper;
App.js
import React from 'react';
import Wrapper from './wrapper';
return (
<Wrapper>
<h2>Hi There!</h2>
<p>This does not work</p>
</Wrapper>
);
Those are the best 3 Solutions to solve this problem.