In React, when you want to return more than one element from a component, you usually wrap them in a div
to satisfy the requirement of returning a single element. However, this approach adds an unnecessary div
to the output. To avoid this, you can use React.Fragment
.
Here’s an example of how to use React.Fragment
:
import React, { Component, Fragment } from 'react';
class BlogPostExcerpt extends Component {
render() {
return (
<React.Fragment>
<h1>{this.props.title}</h1>
<p>{this.props.description}</p>
</React.Fragment>
);
}
}
In recent releases of React (and Babel 7+), there is also a shorthand syntax available using <>
and </>
for React.Fragment
:
import React, { Component, Fragment } from 'react';
class BlogPostExcerpt extends Component {
render() {
return (
<>
<h1>{this.props.title}</h1>
<p>{this.props.description}</p>
</>
);
}
}
Using React.Fragment
or the shorthand syntax <></>
allows you to group multiple elements without the need for an additional container tag like div
.