Why do we have to wrap React components?
Understand div wrapping in your React Apps!
The Problem
So when you first start using react, you will have no doubt written something like the below
const App = () => {
return(
<p>Hello</p>
<p>World</p>
)
}
What’s wrong with that you might ask?
React tries to convert our JSX and this pops out
Failed to compile.
./src/App.js
Syntax error: Adjacent JSX elements must be wrapped in an enclosing tag (6:8)
Behind the scenes for all the JSX statement you write in a component, they need to be wrapped into one container. But wait why is it necessary?
Behind the Scenes of React
To answer this problem we have to think about what happens when React turns our JSX into eventually the HTML we see on the page. The first step in this process is to convert any JSX statement into an object. Behind the scenes, React takes our JSX and a transpiler like Babel feeds the parts of that JSX into the React.createElement
function.
If we look at the API for createElement
function createElement(elementType, props, …children) {}
The arguments are defined as
elementType
— The HTML Tag you want to displayprops
— Data like attributes or styling you want to passchildren
— Anything you want to pass between the eventual HTML tags, most likely
some text but can be other things (see below!)
Here’s the example of our JSX from above
<p>Hello</p> // JSX
Becomes
React.createElement(<p>, null, 'Hello')
The React.createElement
function takes only one 'elementType', that is the <p>
part of our JSX element we want to eventually display.
We can’t have two JSX statements that individually have separate React.createElement
functions. This means two return statements and React will throw an error! Each function must only return one value in JavaScript.