@composi/core:

Fragment

Using Fragments in Functional Components

When defining the markup for components, you may find that you want a way to group a number of siblings together as one component. The Fragment tag allows you to do this.

Importing

Before we can use fragments, we need to import Fragment from @composi/core:

import { h, render, Fragment } from '@composi/core'

After importing it from @composi/core, it is ready to use.

Usage

How to Use Fragments

@composi/fragment is a custom function for JSX. It does one thing, returns its children as an array. This allows you to group a series of sibling element together for use by another component. You would typically do this for lists or table cells. But you can use it for any situation where you want to group several items together.

To use Fragment just put the sibings inside it and return it:

See the Pen @composi/core - Fragment by Robert Biggs (@rbiggs) on CodePen.

Here's another example with buttons:

See the Pen @composi/core - Fragment-2 by Robert Biggs (@rbiggs) on CodePen.

Short Form: <></>

Since create-composi-app makes projects using Babel 7, you can use the shortened form for Fragment: <></>

import { h, render, Fragment } from '@composi/core'

        function ListItems() {
          // Return fragment:
          return (
            <>
              <li>One</li>
              <li>Two</li>
              <li>Three</li>
            </>
          )
        }
        

To be able to use this shorten form with Babel, you need to let Babel know to use it with Composi's fragment by updating your .babelrc file with a pragmaFrag value:

"plugins": [
          [
            "@babel/plugin-transform-react-jsx",
            {
              "pragma": "h",
              "pragmaFrag": "Fragment"
            }
          ]
        ]
        

No Attributes for Fragments

Since Fragments are not real elements, you can't give them any attributes. When the JSX is compiled to a virtual node, the Fragments are discarded and only their children are returned. The Fragment's children become the children of the Fragment's parent node. This means you cannot assign an id, class or key to a Fragment. You can, however, pass them props. Notice how we pass data to the ListItems tag:

import { h, render, Fragment } from '@composi/core'

        function ListItems({data}) {
          return (
            <>
              {
                data.map(item => <li>{item}</li>)
              }
            </>
          )
        }

        function List({data}) {
          return (
            <ul>
              <ListItems data={data} />
            </ul>
          )
        }

        render(<List data={[1,2,3]} />, 'section')