When writing React code , you would have encountered an error related to React asking to render a single DOM
element. At this point, the simplest workaround is that you encapsulate the elements by a pair of outer div tags.
However, have you ever wondered
- What is the real reason behind this error?
- Is this a React bug ?
- How to resolve this error?
- What are the pros and cons of packing elements into div tags above?
Why render single DOM element?
In this article I will try to help you answer the above questions.
Let's say i have a component that goes as follows:
class App extends React.Component {
render() {
return (
<div> Type: Dog </div>
<div> Type: Cat </div>
)
}
}
I have used JSX to define the above component render. However, this is just "syntactic sugar" for the
React.createElement (component, props, ... children) method
Therefore, the above code would be equivalent to the following code:
class App extends React.Component {
render() {
return (
React.createElement('div', null, 'Type: Dog')
React.createElement('div', null, 'Type: Cat')
)
}
}
In the code above, each React.createElement function will return a React Element. That means the function render () of the App class will return 2 elements simultaneously.
This is completely impossible with functions in JavaScript in particular and any other programming language in general, not just React.
For example, Let's look at a function in pure JavaScript as follows:
const func = (x, y) => {
return (x + y)(x - y);
};
The above function func is an arrow function - that returns simultaneously (x + y) and (x - y) . And ofcourse we will get an error.
In short, React's request to render the single DOM element is required, not due to React's bug.
Ways to solve render single DOM element problem?
To solve the above problem, There are 3 ways as below.
1. Use one more tag to encapsulate the Elements
This is the easiest way that almost anyone can think of first. That is using one tag to encapsulate the Elements.
Then, the code above becomes:
class App extends React.Component {
render() {
return (
<div className="app">
<div> Type: Dog </div>
<div> Type: Cat </div>
</div>
);
}
}
2. Using React.Fragment
You can use React.Fragment as follows to solve the problem:
class App extends React.Component {
render() {
return (
<React.Fragment>
<div> Type: Dog </div>
<div> Type: Cat </div>
</React.Fragment>
);
}
}
3. Using <> </>
class App extends React.Component {
render() {
return (
<>
<div> Type: Dog </div>
<div> Type: Cat </div>
</>
);
}
}
Note: This is just a shortened syntax for React.Fragment, not a completely different way.
Epilogue
So, I've covered why React requires rendering of a single DOM element. And some ways to help you fix the above error are:
- Using an extra pair of tags packing the Elements
- Using React.Fragment
- Using <> </> In addition to the above methods, do you know any other ways? If yes, share it with me and everyone!
Top comments (0)