Skip to content
Mithril.js 2
Main Navigation GuideAPI

English

简体中文
繁體中文
Español
Français
Русский
Português – Brasil
Deutsch
日本語
한국어
Italiano
Polski
Türkçe
čeština
magyar

English

简体中文
繁體中文
Español
Français
Русский
Português – Brasil
Deutsch
日本語
한국어
Italiano
Polski
Türkçe
čeština
magyar

Appearance

Sidebar Navigation

API

Core API

m

m.render

m.mount

m.route

m.request

m.parseQueryString

m.buildQueryString

m.buildPathname

m.parsePathname

m.trust

m.fragment

m.redraw

m.censor

Optional API

Stream

Guide

On this page

fragment(attrs, children) ​

Description ​

Allows attaching lifecycle methods to a fragment vnode

javascript
var groupVisible = true;
var log = function () {
  console.log('group is now visible');
};

m('ul', [
  m('li', 'child 1'),
  m('li', 'child 2'),
  groupVisible
    ? m.fragment({ oninit: log }, [
        // a fragment containing two elements
        m('li', 'child 3'),
        m('li', 'child 4'),
      ])
    : null,
]);

Signature ​

Generates a fragment vnode

vnode = m.fragment(attrs, children)

ArgumentTypeRequiredDescription
attrsObjectNoHTML attributes or element properties
childrenArray<Vnode>|String|Number|BooleanNoChild vnodes. Can be written as splat arguments
returnsVnodeA fragment vnode

How to read signatures

How it works ​

m.fragment() creates a fragment vnode with attributes. It is meant for advanced use cases involving keys or lifecyle methods.

A fragment vnode represents a list of DOM elements. If you want a regular element vnode that represents only one DOM element and don't require keyed logic, you should use m() instead.

Normally you can use simple arrays or splats instead to denote a list of nodes:

javascript
var groupVisible = true;

m(
  'ul',
  m('li', 'child 1'),
  m('li', 'child 2'),
  groupVisible
    ? [
        // a fragment containing two elements
        m('li', 'child 3'),
        m('li', 'child 4'),
      ]
    : null
);

However, JavaScript arrays cannot be keyed or hold lifecycle methods. One option would be to create a wrapper element to host the key or lifecycle method, but sometimes it is not desirable to have an extra element (for example in complex table structures). In those cases, a fragment vnode can be used instead.

There are a few benefits that come from using m.fragment instead of handwriting a vnode object structure: m.fragment creates monomorphic objects, which have better performance characteristics than creating objects dynamically. In addition, using m.fragment makes your intentions clear to other developers, and it makes it less likely that you'll mistakenly set attributes on the vnode object itself rather than on its attrs map.

Pager
Previous pagem.trust
Next pagem.redraw

Released under the MIT License.

Copyright (c) 2024 Mithril Contributors

https://mithril.js.org/fragment.html

Released under the MIT License.

Copyright (c) 2024 Mithril Contributors