React - Fragment

About

A component / elements return always a fragment (A part of the React tree)

When a component returns multiple stacked components, you need to wrap them:

  • around a div element
  • or a React.Fragment component (to avoid adding an HTML element)

Example

Jsx

  • Fully qualified name
render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}
  • Simplified
render() {
  return (
    <>
      <ChildA />
      <ChildB />
      <ChildC />
    </>
  );
}

React API

In the low-level React Javascript API. You would create an element with the tag React.Fragment

Example:

  • The function component that returns a fragment of two elements: h1 and div
function ComponentWithFragment(props) {
   return React.createElement(
            React.Fragment, // a fragment element 
            null, // no key props
            React.createElement("h1", null, "Fragment all the way"), // first sub element
            React.createElement("div", null, "Is what we can"), // second sub element, ...
   );
}
let componentWithFragmentElement = React.createElement(ComponentWithFragment);
let root = document.createElement('div');
document.body.append(root);
ReactDOM.render(componentWithFragmentElement , root );
  • The output:

1)





Discover More
How to inject multi React components in a page? A Multiple Root demo

This page shows how to render multiple root in the same web page For instance, when you want to integrate React component in another HTML application (php, ruby,...) with templating, you may render several...
What is a React Element?

An element is a node in the React tree (React DOM implementation) that has a type and props. component getting started createElementjsx filescreateElement e A counter component with a useState...
What is a React Node?

A react node is a node in the React DOM tree. A node may have the following data type: a React Element a React Fragment a React Portal (floating element) and the base Javascript data type:...



Share this page:
Follow us:
Task Runner