Frameworks
The same components, in the way you build: the vanilla factories, web components, or the React, Vue, Svelte and SolidJS components. Pick your framework with the chips above; this page shows its guide, and the rest of the documentation follows the same choice. Getting started covers the install and the base stylesheet.
The factories are material itself: one function per component, which builds its DOM and returns an
object to drive it. There is no framework, no custom element and no shadow root, so the
component's markup is in your page, styled by one stylesheet you import. The web components
and the framework components are built on these factories. Getting started
covers the install and the base stylesheet; this page covers what is specific to the factories.
Create a component
Each component has a create* factory that takes one config object. Every option is optional,
and each component page lists them.
import { createSwitch } from 'material';
const wifi = createSwitch({ label: 'Wi-Fi', checked: true });
document.querySelector('#settings')!.append(wifi.element);
The factory returns the component: element, its root DOM element, and the methods that change
it. The element is not in the page yet: put it wherever it belongs, as you would any element you
created.
The overlays are the exception. A menu, a tooltip and a dialog put their surface on
document.body themselves (the dialog and the menu take a container to go elsewhere), because
they must float above the page. See the top layer for the option
that keeps them in place.
Listen to events
on(event, handler) adds a listener and off(event, handler) removes it. Both return the
component, so they chain. The handler receives a plain object, not a DOM Event: the switch's
change carries { checked, value }, a text field's input carries { value, isEmpty }. Each
component page's Events table lists its events and their fields.
wifi.on('change', ({ checked }) => setWifi(checked));
To remove a listener, keep the function you added:
import createTextField from 'material/components/text-field';
import type { TextFieldEvents } from 'material/components/text-field';
const query = createTextField({ label: 'Search' });
const onInput: TextFieldEvents['input'] = ({ value }) => runSearch(value);
query.on('input', onInput);
query.off('input', onInput);
Setters are not all silent. check() on a switch emits change, as a click does, while a text
field's setValue() emits nothing. Don't use a listener to tell the user's changes from your
own; keep that in your code.
Setters and methods
A component's state changes through its methods, never through its classes or attributes:
check(), disable(), a text field's setValue('Paris'). Getters read it back:
isChecked(), getValue(). Most setters return the component, so calls chain.
const airplane = createSwitch({ label: 'Airplane mode', checked: true });
airplane.uncheck().disable();
The methods keep the component's parts in step: disable() on a switch disables its inner
input and sets the root's --disabled class together. Changing the DOM directly skips that, and
the next method call may undo it.
Destroy what you remove
destroy() removes the component's element from the page, removes its listeners, and releases
what it holds outside its element: listeners on document or window, observers, timers. A
menu, for instance, listens on the document for outside clicks and on the window for resizes.
Removing only the element leaves all of that running, and it keeps the component in memory.
const bluetooth = createSwitch({ label: 'Bluetooth' });
document.body.append(bluetooth.element);
// When the view goes away
bluetooth.destroy();
Call it whenever a view that created components goes away. After destroy(), the component is
done: create a new one to show it again.
Styles
Import the base stylesheet once, then one stylesheet per component you use:
import 'material/styles/base';
import 'material/styles/switch';
import 'material/styles/select';
A component's stylesheet brings those it depends on: material/styles/select also loads the text
field's and the menu's. The alternative is material/styles, one file with every component and the
bundled themes. It is simpler, and several times larger than a page with a few components needs.
Other themes are their own imports (material/themes/<name>), as Getting
started shows.
The classes are BEM, with the mtrl- prefix (mtrl-switch__track), and the colours, type and
shapes come from --mtrl-sys-* custom properties. Each component page's Styling section lists
the classes and properties meant to be overridden.
Import paths and tree-shaking
The package is free of side effects apart from its stylesheets, so a bundler keeps only what you import. Two paths reach a factory, and both tree-shake:
import { createButton, createMenu } from 'material';
import createDialog from 'material/components/dialog';
The root entry has every factory and its main types. material/components/<name> has one component,
its factory as the default export, with its types and constants. The constants are only
there: import { BUTTON_VARIANTS } from 'material/components/button/constants'. The composition
utilities are in material/core; Architecture shows how to build on them.
Some features load on demand: a menu's submenus are a separate chunk, fetched only by a menu that has nested items. Your bundler splits them out on its own.
Overlays and the top layer
By default, the overlays live on document.body and stack by z-index. The layer: "top"
option renders them in place, beside their opener or in their container, and shows them in the
browser's top layer: above every z-index, outside any overflow: hidden parent, and inside the
opener's shadow root if it has one. Menus, tooltips and snackbars open as popovers; dialogs,
modal sheets and the modal drawer with showModal(), which makes the rest of the page inert and
turns the scrim into the dialog's ::backdrop.
const sort = createButton({ text: 'Sort' });
document.querySelector('#toolbar')!.append(sort.element);
const menu = createMenu({
opener: sort,
items: [
{ id: 'name', text: 'Name' },
{ id: 'date', text: 'Date' },
],
layer: 'top',
});
menu.on('select', ({ itemId }) => showView(itemId));
The option exists on the menu, select, split button, tooltip, snackbar, dialog, bottom and side
sheets, and drawer. It is off by default, and where the browser has no popover or showModal()
support it does nothing. The web components use it for every overlay.
When to choose Vanilla
Choose the factories for the smallest bundles and full control: no element layer, no shadow root,
no framework runtime. They suit a page without a framework, a framework material has no components
for, or a component you drive from your own state code. Each component page shows, beside its
name, what the component adds to an app, minified and gzipped: with Vanilla selected in the
switch at the top, that is the factory's size, and with any other choice, the web component's.
The difference is the element layer the other flavours share.
Choose the web components when your markup is HTML, or React and the other adapters when your app is written in one.
material/elements has every component as a custom element: <m-switch>, <m-tabs>, <m-dialog>.
Each element builds its factory inside its own shadow root, so it works in plain HTML, server
templates and any framework. Getting started covers the install and the
styles; this page covers what is specific to the elements.
Register the elements
Importing material/elements registers nothing and touches no DOM, so it is safe on a server.
defineAll() registers every element; to ship less, register those you use, each with its CSS:
import 'material/elements/css/switch';
import { defineSwitch } from 'material/elements';
defineSwitch();
Without its CSS, a define* function warns and names the import. Registering twice is
harmless, so two bundles on one page, or a hot reload, don't throw. The tags start with m-;
pass a prefix to use your own:
import 'material/elements/css';
import { defineAll } from 'material/elements';
defineAll({ prefix: 'md' });
The page then uses <md-switch>, <md-tabs>, and so on.
Deferred menu registration
material/elements/menu is a dedicated entry exporting defineMenu; importing it registers
nothing. The eager registration is:
import 'material/elements/css/menu';
import { defineMenu } from 'material/elements/menu';
defineMenu();
To defer a closed menu, load material/elements/preupgrade/menu.css before upgrade, then defer
both material/elements/menu and material/elements/css/menu. Call defineMenu() when both
imports resolve; callers must await registration before using element methods. Initially open
menus need eager registration and ready styles. See Menu.
Attributes and properties
Attributes have a property of the same name, in camelCase (supporting-text is
supportingText), and setting one sets the other; the label fallback of a slotted label is,
for now, an attribute only. Rich values, such as a menu's anchor element, are properties only.
The value is the exception, as on a native <input>. A switch's checked attribute, or a text
field's value, is the default: it sets the state, and moves it when it changes, until the
user or a script changes the state. From then on the property holds it, the attribute stays as
it was, and a form reset returns to it.
import type { SwitchElement } from 'material/elements';
const wifi = document.querySelector('m-switch') as SwitchElement;
wifi.checked = false; // the live state
wifi.hasAttribute('checked'); // the default, unchanged
Interaction never writes a default, so a framework that owns the attributes never sees them
change under it. Only what opens and closes is reflected: the overlays' open and a rail's
expanded, as open is on <dialog>.
Most attributes update the component in place. A few, such as a button's icon, are read at
creation: changing one rebuilds the component inside, keeping its state. Methods are forwarded:
wifi.toggle(), dialog.show(). A property set before the element is defined is kept.
Events
An element dispatches its factory's events from the host, under the same names, as
CustomEvents that bubble and cross shadow roots. The payload is in detail: { checked, value, valueAttribute }
for a switch's change, where value is the boolean and valueAttribute is the input's value attribute. Each component page lists them.
wifi.addEventListener('change', (event) => {
const { checked } = (event as CustomEvent<{ checked: boolean }>).detail;
setWifi(checked);
});
The inner controls' native change and input stay inside, so you receive only the host's.
Events report the user's changes and those of a method (toggle()), never a property you set or
an attribute that changed. A dialog's cancel, on Escape, can be refused with
preventDefault().
Children, declarations and slots
A composite reads its items from children that render nothing: <m-tab> in <m-tabs>,
<m-radio> in <m-radios>, <m-menu-item> in <m-menu>, <m-select-option> in <m-select>,
and so on. Their text is the label, unless they have a label attribute. The parent watches
them, so adding, removing or editing one updates it.
<m-tabs value="songs">
<m-tab value="songs">Songs</m-tab>
<m-tab value="albums">Albums</m-tab>
</m-tabs>
Other content goes into slots. A button's, switch's or checkbox's children are its label, with
the label attribute as the fallback. A dialog has a headline slot, a default slot for its
content, and an actions slot.
<m-dialog headline="Discard draft?">
Your changes will be lost.
<div slot="actions">
<m-button variant="text">Cancel</m-button>
<m-button variant="text">Discard</m-button>
</div>
</m-dialog>
An element has no destroy(). Removing it destroys its factory; moving it (a keyed reorder)
keeps it; one that comes back is built again from its attributes.
Forms
The switch, checkbox, radios, slider, text field, select, search, date picker and time picker are form-associated, as native controls are.
- Value: the element submits under its
name, andnew FormData(form)reads it. A switch or a checkbox submits itsvalue(oron) when checked, and nothing otherwise. - Reset:
form.reset()returns each control to its attributes. - Validity:
required, and a text field'spattern, set the element's validity: an invalid control blocks the submit and matches:invalid. - Restore: when the browser restores a form (a back navigation, an autofill), each control gets its value back.
- Labels: a
<label for>pointing at the element activates it: it toggles a switch, focuses a text field. A disabled<fieldset>disables the controls in it.
<m-button type="submit"> submits its form, and type="reset" resets it.
<form>
<label for="city">Where to?</label>
<m-text-field id="city" name="city" label="City" required></m-text-field>
<m-switch name="newsletter" value="yes">Send me offers</m-switch>
<m-button type="submit">Book</m-button>
</form>
Styling from outside
Use material/styles/base-elements for element and framework pages keeping the baseline
light/dark theme, colour/shape/typeface tokens, reset, cascade order and system contrast
(prefers-contrast: more). Its bundled CSS saves 293 B gzip (970 B raw) against material/styles/base by
omitting global light-DOM ripple rules already carried by each element's shadow root.
Use base for factories or page-level data-ripple, or material/styles/base-lite for element
pages omitting the reset and contrast modes. Explicit data-theme-contrast still needs
material/styles/contrast. Choose one base; the typography JavaScript entry imports the full
base, so see Theming for loading typography CSS separately.
The shadow root keeps the page's CSS out, except what inherits. The chosen base and themes
stay in the page: the --mtrl-sys-* colour, type and shape tokens are custom properties, which
inherit, so a data-theme on an ancestor themes every element in it. A component's own custom
properties work the same way:
m-button {
--mtrl-button-shape: 8px;
}
The host is the box you lay out: inline-block unless the component is a block, such as a
card. A text field fills the width you give it. Selectors can't reach inside, and the elements
expose no ::part yet: the custom properties are the styling surface.
Application-compiled element styles
To opt custom elements into the Sass typography role-fallback profile ($typescale-tokens: true),
or configure $tag-prefix and $contrast-emit once through material/src/styles/config (see
Theming):
Compile matching pre-upgrade CSS through
material/src/styles/preupgrade(which includes themtrl.preupgradelayer and linked-SSR rollback; add$tag-prefix: "md"when registering elements under{ prefix: 'md' }):@use "material/src/styles/config" with ($typescale-tokens: true); @use "material/src/styles/preupgrade";Compile each required shadow style key through the experimental
material/src/styles/element-stylesentry:@use "material/src/styles/config" with ($typescale-tokens: true); @use "material/src/styles/element-styles" with ($name: "button");Load
material/styles/base-elementsand register every required key (ripple,progressandbuttonfor a button; other elements require their own complete key set) withregisterStylesbefore callingdefineButton():import 'material/styles/base-elements'; import { defineButton, registerStyles } from 'material/elements'; const names = ['ripple', 'progress', 'button']; const sheets = await Promise.all(names.map(async name => { const response = await fetch(`/app-css/${name}.css`); if (!response.ok) throw new Error(`Cannot load ${name} styles`); return [name, await response.text()]; })); registerStyles(Object.fromEntries(sheets)); defineButton();
Role properties (--mtrl-sys-typescale-<role>-*) inherit through element hosts into shadow roots.
Applications own the compiled files, their loading and the additional CSS cost. Register styles
before defining or creating elements — later registerStyles calls do not replace sheets already
adopted by existing shadow roots. Normal framework adapter entries keep their default CSS imports.
For linked SSR (styles: 'link'), point cssBase at the app-compiled shadow CSS directory while
supplying component dependencies and unchanged host sheets from dist/elements/css (default inline
SSR retains its default CSS).
Server-rendered HTML
Until its script defines it, an element is the markup the server sent, unstyled. The pre-upgrade
stylesheet gives each element its final box meanwhile, so nothing jumps when it upgrades: labels
in their final type style, declaration children hidden with their room kept, overlays hidden.
An element's own CSS does not include them. For server-rendered pages, put
them in the <head> so they apply from the first paint:
<link rel="stylesheet" href="/css/mtrl-preupgrade.css">
The file is material/elements/preupgrade.css: serve a copy, or import it where your bundler handles
CSS. It is built for m-; for another prefix, build the rules on the server and inline them, or
compile material/src/styles/preupgrade with material/src/styles/config in Sass:
import { preupgradeStyles } from 'material/elements/preupgrade';
const css = preupgradeStyles('md');
The top layer
Menus, selects, split buttons, tooltips, snackbars, dialogs, modal sheets, the modal drawer and
rail, search's view and the pickers open in the browser's top layer from inside their shadow
root: above every z-index, outside any overflow: hidden parent, with nothing to configure.
The modals use showModal(), so the page outside is inert. A menu's anchor and a tooltip's
for name their target by id, in the element's own root first, then the document:
<m-button id="sort">Sort</m-button>
<m-menu anchor="sort">
<m-menu-item value="name">Name</m-menu-item>
<m-menu-item value="date">Date</m-menu-item>
</m-menu>
Many instances
Each element styles its own shadow root, and the first render of many elements costs more than
the same factories in the page. Measured on material 3.0.0-next.0 in Chromium 153, 1,000 text
fields mount in about 290 ms as elements against about 150 ms as factories; with the CPU slowed
four times, in about 1.4 s against about 0.63 s. These are medians of 15 runs.
A form or a page has far fewer. For hundreds of instances created at once, a long editable table for example, use the Vanilla factories there; they mix with the elements on the same page.
The React, Vue, Svelte and SolidJS components render these elements, so all of this holds there too; their guides cover what each framework adds.
material/react has a React component for every element: Switch renders <m-switch>, Tabs
renders <m-tabs>. The element does the work, so everything in the Web Components
guide holds here: the forms, the styling, the top layer. Getting
started covers the install and the base stylesheet; this page covers what
the React components add.
Components and props
Import the components by name. material/react loads the elements' CSS, and each component
registers its element the first time it mounts, so there is no defineAll() to call.
import { Switch, TextField } from 'material/react';
export function Settings() {
return (
<form>
<TextField name="city" label="City" supportingText="Where you live" variant="outlined" />
<Switch name="wifi" defaultChecked>Wi-Fi</Switch>
</form>
);
}
The props are the element's attributes and properties in camelCase, typed from the element:
supportingText is the supporting-text attribute. Form controls take name. Any other prop,
such as id, style, aria-*, data-* or a React event like onClick, goes to the host
element. className works on React 18 and 19 alike: the component passes it on as class.
To render another tag prefix, call configure once, before the first render:
import { configure } from 'material/react';
configure({ prefix: 'md' });
Events
Each element event is an on prop: change is onChange, select is onSelect. The handler
receives the element's CustomEvent, with the payload in event.detail, typed for each
component. They replace React's own handlers of the same name, and keep the element's meaning:
a TextField's onChange follows the native change, when the edit is committed, not React's
per-keystroke onChange. Use onInput for every keystroke; both carry { value }.
The component attaches its listeners once and always calls your latest handler, so an inline arrow function costs nothing.
A component owns the on… props of its element's events (onChange, onInput, onSelect,
…) and its default… props, typed with the element's own payloads. Any other HTML attribute
passes to the host. To spread a whole set of HTML attributes into a component, omit the props
it owns:
type Rest = Omit<React.HTMLAttributes<HTMLElement>, 'onChange'>;
Controlled and uncontrolled
The components follow React's inputs. Give the value prop (checked, value) and it is
controlled: the component writes it to the element after every render, and if your handler
doesn't change it, puts it back, as React does for <input checked>.
import { useState } from 'react';
import { Switch } from 'material/react';
export function WifiSetting() {
const [wifi, setWifi] = useState(false);
return (
<Switch checked={wifi} onChange={(event) => setWifi(event.detail.checked)}>
Wi-Fi
</Switch>
);
}
Give defaultChecked or defaultValue instead, or nothing, and it is uncontrolled: that
prop is the element's default attribute, the element keeps its own state, and a form reset
returns to the default. Read the value from onChange, from a ref, or from the form.
The props that work this way are the element's live state: checked on a switch or a checkbox,
value on a text field, select, slider, tabs or radio group, and a few more. The other props are
settings, which the element follows on every render.
Forms
The form controls are form-associated elements, so a plain <form> sees them: they submit under
their name, and new FormData(form) reads them. That makes uncontrolled components a good fit
for React 19's form actions, which receive the FormData:
import { Button, Switch, TextField } from 'material/react';
export function Booking() {
return (
<form action={(data) => submitForm(data)}>
<TextField name="city" label="City" required />
<Switch name="newsletter" value="yes">Send me offers</Switch>
<Button type="submit">Book</Button>
</form>
);
}
A required field that is empty blocks the submit, as a native input does, and the form's reset
after an action returns each control to its default.
Refs
ref gives you the element, with its properties and methods typed. The element types come from
material/elements:
import { useRef } from 'react';
import { Button, TextField } from 'material/react';
import type { TextFieldElement } from 'material/elements';
export function Rename() {
const field = useRef<TextFieldElement>(null);
return (
<>
<TextField ref={field} label="Name" defaultValue="Untitled" />
<Button onClick={() => field.current?.select()}>Select all</Button>
</>
);
}
Methods such as select(), toggle(), show() and close() are the element's, as the
component pages list them. focus() is the host's, and moves focus to the control inside.
Children and slots
Children go into the element, as in HTML. Text is the label of a button, switch or checkbox.
A composite's items are declaration components, named as their tags: Tab for <m-tab>,
MenuItem, SelectOption, Radio. A named slot is a prop of its name that takes JSX, such as
a dialog's actions or a card's headerAction; headline takes text for the attribute or JSX
for the slot. Each component's page lists its slots.
import { useState } from 'react';
import { Button, Dialog, Tab, Tabs } from 'material/react';
export function Library() {
const [tab, setTab] = useState<string | null>('songs');
const [confirming, setConfirming] = useState(false);
return (
<>
<Tabs value={tab} onChange={(event) => setTab(event.detail.value)}>
<Tab value="songs">Songs</Tab>
<Tab value="albums">Albums</Tab>
</Tabs>
<Dialog
headline={<strong>Discard draft?</strong>}
actions={<Button variant="text" onClick={() => setConfirming(false)}>Cancel</Button>}
open={confirming}
onClose={() => setConfirming(false)}
>
Your changes will be lost.
</Dialog>
</>
);
}
Bare tags in JSX
The components are the usual way. To write the elements themselves (<m-switch checked>),
import the tag types once, in any file TypeScript sees:
import type {} from 'material/react/jsx';
export const Wifi = () => (
<m-switch checked label="Wi-Fi" onchange={(event) => setWifi(event.detail.checked)} />
);
It is types only, so nothing reaches the bundle; the element still needs defineAll() or its
define function, as in Web Components. On a bare tag, listen with the
lowercase onchange: React 19 hands onChange its own synthetic event, without detail, and
React 18 sets no event props on custom elements at all. The components (<Switch onChange>)
have none of these differences.
React 18 and 19
The components behave the same on both, and the adapter is checked on both. They set
properties and attach listeners themselves, rather than relying on React 19's support for custom
elements, and they use forwardRef, so refs work on 18 too. There is nothing to change when you
upgrade.
Next.js and server rendering
material/react starts with "use client", so you can import the components from Server
Components: they are client components, which Next.js still renders on the server. Event
handlers and refs need a client component of your own, as with any client component. The server
HTML is the element's tag with its attributes: the string, number and boolean props, a
controlled value as its default attribute, and the children. Objects, functions and listeners
wait for hydration. The element is registered in the browser on first mount, never at import.
Until then, the server's <m-switch> has no shadow root. Import the pre-upgrade stylesheet
once, in the root layout, so each element has its final box from the first paint and nothing
shifts when it upgrades:
import type { ReactNode } from 'react';
import 'material/styles/base';
import 'material/elements/preupgrade.css';
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
Bundle size
Each component is its own module: importing Switch brings the switch element and its CSS, and
nothing else. A component costs about 1 KB gzip more than its web component, and each component
page shows its size. For the smallest bundles, the Vanilla factories skip the
element layer altogether.
material/vue has a Vue 3 component for every material web component, for Vue 3.3 or later and Nuxt.
Each one renders its <m-*> element, so it looks and behaves exactly as the element does. This
page covers only what is particular to Vue; Getting started has the
install and the base stylesheet, and each component page has its options and events.
Components
The components are named after the element with an M in front: MButton, MSwitch,
MTabs, MTextField. Import them where you use them:
<script setup lang="ts">
import { MButton, MSwitch } from 'material/vue';
</script>
<template>
<MSwitch>Wi-Fi</MSwitch>
<MButton variant="filled">Save</MButton>
</template>
There is no plugin to install. For global registration, pass them to app.component() as you
would any component. A component registers its element the first time it mounts, and importing
material/vue loads the elements' styles, so the base stylesheet is the only CSS you add.
<m-switch> written directly in a template is the web component itself, which Vue first tries
to resolve as a Vue component and warns about. If you mix bare elements in, tell the compiler
they are custom elements with compilerOptions.isCustomElement: (tag) => tag.startsWith('m-')
(in @vitejs/plugin-vue's template options, or vue.compilerOptions in nuxt.config). The
M components don't need it.
Props
A component's props are its element's attributes, written as any Vue prop: kebab-case or
camelCase, bound with : for numbers, booleans and expressions.
<script setup lang="ts">
import { MSlider, MTextField } from 'material/vue';
</script>
<template>
<MTextField label="Email" type="email" supporting-text="We never share it" required />
<MSlider aria-label="Volume" :min="0" :max="100" :step="5" />
</template>
They are rendered as attributes, so server markup carries them. false removes a boolean
attribute. Anything else you pass, such as class, id or data-*, lands on the element as
Vue's fallthrough attributes do.
The live state (checked, value, selected) is a prop too, written to the element as a
property. Its attribute is the element's default, as checked is on a native checkbox, and
takes the default prefix: default-checked, default-value.
Events
Each element event is a Vue event of the same name: @change, @input, @open, @close,
@select. The payload is the element's CustomEvent, with the data in detail; every
component page lists its events and their fields.
<script setup lang="ts">
import { MSwitch, MTextField } from 'material/vue';
function setWifi(on: boolean) {
console.log('Wi-Fi', on);
}
function search(query: string) {
console.log('Searching for', query);
}
</script>
<template>
<MSwitch @change="setWifi($event.detail.checked)">Wi-Fi</MSwitch>
<MTextField label="Search" @input="(event) => search(event.detail.value)" />
</template>
The events are typed, so event.detail is checked in your editor. Native events such as
@click or @focus are not the component's own: they fall through to the element, and the
handler receives the browser's event.
v-model
v-model binds the element's model: the property that holds its value.
| Components | v-model binds |
|---|---|
MSwitch, MCheckbox |
checked |
MIconButton (a toggle) |
selected |
MCarousel |
index |
MTextField, MSlider, MSelect, MRadios, MTabs, MChips, MList, MSearch, MDatepicker, MTimepicker, MNavigationRail, MDrawer, MButtonGroup |
value |
Under it are modelValue and update:modelValue. Every live property also has its own
v-model:<name>, such as v-model:indeterminate on a checkbox.
<script setup lang="ts">
import { ref } from 'vue';
import { MSwitch, MTabs, MTab } from 'material/vue';
const wifi = ref(true);
const tab = ref('songs');
</script>
<template>
<MSwitch v-model="wifi">Wi-Fi</MSwitch>
<MTabs v-model="tab">
<MTab value="songs">Songs</MTab>
<MTab value="albums">Albums</MTab>
</MTabs>
<p>Wi-Fi is {{ wifi ? 'on' : 'off' }}, showing {{ tab }}.</p>
</template>
The binding updates after each of the element's events, so a text field's v-model follows
every keystroke. A prop without a listener doesn't hold the element: as with a native input,
:checked="false" alone lets the user turn the switch on. Bind with v-model, or pair the prop
with its event.
A dialog, a sheet or a menu opens from its open attribute. Bind it, and put your state back in
step when the user closes it:
<script setup lang="ts">
import { ref } from 'vue';
import { MButton, MDialog } from 'material/vue';
const open = ref(false);
</script>
<template>
<MButton @click="open = true">Delete</MButton>
<MDialog :open="open" headline="Delete draft?" @close="open = false">
<p>The draft will be deleted for good.</p>
<template #actions>
<MButton variant="text" @click="open = false">Cancel</MButton>
<MButton variant="text" @click="open = false">Delete</MButton>
</template>
</MDialog>
</template>
Slots and children
The default slot becomes the element's children: a button's label, a dialog's or a card's
content. A component's named regions, such as a dialog's headline and actions, a card's
header-action or a top app bar's leading and trailing, are Vue named slots: fill them with
<template #actions>, as the dialog above does. A region that also has a text prop, such as
headline or subhead, takes either: the prop for plain text, the slot for markup.
<script setup lang="ts">
import { MButton, MCard } from 'material/vue';
</script>
<template>
<MCard subhead="Updated today">
<template #headline>Release <em>notes</em></template>
<p>What changed in this version.</p>
<template #actions>
<MButton variant="text">Read more</MButton>
</template>
</MCard>
</template>
Lists of items are declared with child components: MTab, MRadio, MChip, MListItem,
MMenuItem, MSelectOption, MSearchSuggestion, MNavigationRailItem, MDrawerItem,
MButtonGroupItem and MCarouselItem. They render nothing themselves; their parent reads them.
Keep them direct children of their parent, with no element in between. v-for and v-if are
fine: the parent reads them again when they change.
<script setup lang="ts">
import { ref } from 'vue';
import { MRadios, MRadio } from 'material/vue';
const sizes = [{ value: 's', label: 'Small' }, { value: 'm', label: 'Medium' }, { value: 'l', label: 'Large' }];
const size = ref('m');
</script>
<template>
<MRadios v-model="size" aria-label="Size">
<MRadio v-for="option in sizes" :key="option.value" :value="option.value">{{ option.label }}</MRadio>
</MRadios>
</template>
Template refs
A template ref gives the component instance, whose element is the <m-*> element, with its
properties and methods. It is null until the component mounts. Exposed types it:
<script setup lang="ts">
import { ref } from 'vue';
import { MButton, MTextField, type Exposed } from 'material/vue';
import type { TextFieldElement } from 'material/elements';
const field = ref<InstanceType<typeof MTextField> & Exposed<TextFieldElement>>();
</script>
<template>
<MTextField ref="field" label="Name" default-value="Ada Lovelace" />
<MButton @click="field?.element?.select()">Select the name</MButton>
</template>
Nuxt and server rendering
The components render on the server. Nuxt's HTML has each element's tag, its attributes and
its slotted children, and a bound value as its attribute: v-model on a switch that is on
renders <m-switch checked>. Every module imports safely without a DOM, and the element
registers in onMounted, so it upgrades as the page hydrates. You don't need <ClientOnly> for
them; keep it for your own browser-only code. A ref's element is null on the server, so
reach it in onMounted or in an event handler.
Until an element upgrades, it has no shadow root and so none of its styles. The pre-upgrade
stylesheet gives each element its final size and look meanwhile, so the page doesn't shift when
the script arrives. Load it globally, in app.vue or in nuxt.config's css:
import 'material/elements/preupgrade.css';
Server rendering explains what the server sends and how the upgrade happens, for every framework.
material/svelte has a Svelte 5 component for every material web component, for Svelte apps and
SvelteKit. Each one renders its <m-*> element, so it looks and behaves exactly as the element
does. This page covers only what is particular to Svelte; Getting started
has the install and the base stylesheet, and each component page has its options and events.
Components
The components are named after the element: Button, Switch, Tabs, TextField. Import
them where you use them:
<script lang="ts">
import { Button, Switch } from 'material/svelte';
</script>
<Switch>Wi-Fi</Switch>
<Button variant="filled">Save</Button>
They ship as .svelte source files, not compiled JavaScript: the package's svelte export
condition points at them, and your build compiles them with your own components. The Svelte
plugin for Vite, which SvelteKit and Vite's Svelte template include, does this without any
setting. They are written with runes, so they need Svelte 5; with Svelte 4, use the
web components directly.
A component registers its element the first time it mounts, and importing material/svelte loads
the elements' styles, so the base stylesheet is the only CSS you add.
Props
A component's props are its element's attributes, in camelCase: supportingText for
supporting-text, ariaLabel for aria-label. Pass numbers and expressions in braces.
<script lang="ts">
import { Slider, TextField } from 'material/svelte';
</script>
<TextField label="Email" type="email" supportingText="We never share it" required />
<Slider ariaLabel="Volume" min={0} max={100} step={5} />
They are rendered as attributes, so server markup carries them. false removes a boolean
attribute. Anything else you pass, such as class, id or data-*, lands on the element.
The live state (checked, value, selected) is a prop too, written to the element as a
property. Its attribute is the element's default, as checked is on a native checkbox, and
takes the default prefix: defaultChecked, defaultValue.
Events
Element events are callback props, lowercase as Svelte 5 names them: onchange, oninput,
onopen, onclose, onselect. The handler receives the element's CustomEvent, with the
data in detail; every component page lists its events and their fields.
<script lang="ts">
import { Switch, TextField } from 'material/svelte';
function setWifi(on: boolean) {
console.log('Wi-Fi', on);
}
function search(query: string) {
console.log('Searching for', query);
}
</script>
<Switch onchange={(event) => setWifi(event.detail.checked)}>Wi-Fi</Switch>
<TextField label="Search" oninput={(event) => search(event.detail.value)} />
The events are typed, so event.detail is checked in your editor. Native events such as
onclick or onfocus are not the component's own: they reach the element as on any tag, with
the browser's event.
Binding
Every live property is $bindable, so bind: works on each of them by its own name:
bind:checked on a switch or a checkbox, bind:selected on a toggle icon button, bind:index
on a carousel, and bind:value on the text field, slider, select, radios, tabs, chips, list,
search, date and time pickers, navigation rail, drawer and button group. Others, such as a
checkbox's indeterminate, bind the same way.
<script lang="ts">
import { Switch, Tabs, Tab } from 'material/svelte';
let wifi = $state(true);
let tab = $state<string | null>('songs');
</script>
<Switch bind:checked={wifi}>Wi-Fi</Switch>
<Tabs bind:value={tab}>
<Tab value="songs">Songs</Tab>
<Tab value="albums">Albums</Tab>
</Tabs>
<p>Wi-Fi is {wifi ? 'on' : 'off'}, showing {tab}.</p>
The binding is written back after each of the element's events, so a text field's
bind:value follows every keystroke. A prop without bind: doesn't hold the element: as with a
native input, checked={false} alone lets the user turn the switch on.
A dialog, a sheet or a menu opens from its open attribute. Pass your state, and put it back in
step when the user closes it:
<script lang="ts">
import { Button, Dialog } from 'material/svelte';
let open = $state(false);
</script>
<Button onclick={() => (open = true)}>Delete</Button>
<Dialog {open} headline="Delete draft?" onclose={() => (open = false)}>
<p>The draft will be deleted for good.</p>
{#snippet actions()}
<Button variant="text" onclick={() => (open = false)}>Cancel</Button>
<Button variant="text" onclick={() => (open = false)}>Delete</Button>
{/snippet}
</Dialog>
Snippets and children
A component's children are its children snippet, which becomes the element's content: a
button's label, a dialog's or a card's text. A component's named regions, such as a dialog's
headline and actions, a card's header-action or a top app bar's leading and trailing,
are named snippets: {#snippet actions()}, as the dialog above does. A dashed name is
camelCase: {#snippet headerAction()}. A region that also has a text prop, such as headline
or subhead, takes either: the prop for plain text, the snippet for markup.
<script lang="ts">
import { Button, Card } from 'material/svelte';
</script>
<Card subhead="Updated today">
{#snippet headline()}Release <em>notes</em>{/snippet}
<p>What changed in this version.</p>
{#snippet actions()}
<Button variant="text">Read more</Button>
{/snippet}
</Card>
Lists of items are declared with child components: Tab, Radio, Chip, ListItem,
MenuItem, SelectOption, SearchSuggestion, NavigationRailItem, DrawerItem,
ButtonGroupItem and CarouselItem. They render nothing themselves; their parent reads them.
Keep them direct children of their parent, with no element in between. {#each} and {#if}
are fine: the parent reads them again when they change.
<script lang="ts">
import { Radios, Radio } from 'material/svelte';
const sizes = [{ value: 's', label: 'Small' }, { value: 'm', label: 'Medium' }, { value: 'l', label: 'Large' }];
let size = $state<string | null>('m');
</script>
<Radios bind:value={size} ariaLabel="Size">
{#each sizes as option (option.value)}
<Radio value={option.value}>{option.label}</Radio>
{/each}
</Radios>
Reaching the element
bind:this on a component gives the component, whose element is the <m-*> element, with
its properties and methods. It is null until the component mounts. An attachment,
{@attach}, gets the element itself when it mounts:
<script lang="ts">
import { Button, TextField } from 'material/svelte';
let field = $state<ReturnType<typeof TextField>>();
</script>
<TextField bind:this={field} label="Name" defaultValue="Ada Lovelace" {@attach (element) => element.focus()} />
<Button onclick={() => field?.element?.select()}>Select the name</Button>
Most of what you would call a method for has a prop or a binding, though: open on a dialog,
bind:checked rather than toggle().
SvelteKit and server rendering
The components render on the server. SvelteKit's HTML has each element's tag, its attributes
and its children, and a bound value as its attribute: a bound switch that is on renders
<m-switch checked>. Every module imports safely without a DOM, and the element registers
when the component mounts in the browser, so it upgrades as the page hydrates. There is nothing
to turn off for the server.
Until an element upgrades, it has no shadow root and so none of its styles. The pre-upgrade
stylesheet gives each element its final size and look meanwhile, so the page doesn't shift when
the script arrives. Import it once in your root +layout.svelte:
import 'material/elements/preupgrade.css';
Server rendering explains what the server sends and how the upgrade happens, for every framework.
material/solid has a SolidJS component for every material web component, for Solid 1.8 or later and
SolidStart. Each one renders its <m-*> element, so it looks and behaves exactly as the element
does. This page covers only what is particular to Solid; Getting started
has the install and the base stylesheet, and each component page has its options and events.
Components and props
The components are named after the element: Button, Switch, Tabs, TextField. Import
them where you use them. A component's props are its element's attributes, in camelCase:
supportingText for supporting-text, ariaLabel for aria-label.
import { Button, Slider, TextField } from 'material/solid';
export function Profile() {
return (
<>
<TextField label="Email" type="email" supportingText="We never share it" required />
<Slider ariaLabel="Volume" min={0} max={100} step={5} />
<Button variant="filled">Save</Button>
</>
);
}
A component registers its element the first time it mounts, and importing material/solid loads
the elements' styles, so the base stylesheet is the only CSS you add.
Props stay reactive: pass a signal's value and the element follows it. On the server they are
rendered as attributes, so the markup carries them. In the browser, Solid sets a custom
element's props as properties; every material element, and every child like <Tab>, has a property
for each attribute, so both reach the same place. false removes a boolean attribute. Anything
else you pass, such as class, id or data-*, lands on the element.
Events
Element events are on props in PascalCase: onChange, onInput, onOpen, onClose,
onSelect. The handler receives the element's CustomEvent, with the data in detail; every
component page lists its events and their fields.
import { Switch, TextField } from 'material/solid';
function search(query: string) {
console.log('Searching for', query);
}
export function Settings() {
return (
<>
<Switch onChange={(event) => console.log('Wi-Fi', event.detail.checked)}>Wi-Fi</Switch>
<TextField label="Search" onInput={(event) => search(event.detail.value)} />
</>
);
}
The events are typed, so event.detail is checked in your editor. Native events such as
onClick or onFocus are not the component's own: Solid handles them as on any tag, with the
browser's event.
Signals, controlled and uncontrolled
Solid has no two-way binding, so a value is controlled as in React: pass the signal's value to
the live property (checked, value, selected) and set the signal from the event. The
component writes the property to the element whenever the signal changes.
import { createSignal } from 'solid-js';
import { Switch, Tabs, Tab } from 'material/solid';
export function Library() {
const [wifi, setWifi] = createSignal(true);
const [tab, setTab] = createSignal<string | null>('songs');
return (
<>
<Switch checked={wifi()} onChange={(event) => setWifi(event.detail.checked)}>Wi-Fi</Switch>
<Tabs value={tab()} onChange={(event) => setTab(event.detail.value)}>
<Tab value="songs">Songs</Tab>
<Tab value="albums">Albums</Tab>
</Tabs>
<p>Wi-Fi is {wifi() ? 'on' : 'off'}, showing {tab()}.</p>
</>
);
}
A controlled prop without its event doesn't hold the element: as with a native input,
checked={false} alone lets the user turn the switch on, and the signal falls out of step.
To leave the state to the element, don't pass the live property. Its attribute is the
element's default, as checked is on a native checkbox, and takes the default prefix:
defaultChecked, defaultValue. Read the value from the event when you need it:
import { Switch } from 'material/solid';
export function Notifications() {
return (
<Switch name="notifications" defaultChecked onChange={(event) => console.log('Notifications', event.detail.checked)}>
Notifications
</Switch>
);
}
A dialog, a sheet or a menu opens from its open attribute. Pass a signal, and set it back when
the user closes it:
import { createSignal } from 'solid-js';
import { Button, Dialog } from 'material/solid';
export function DeleteDraft() {
const [open, setOpen] = createSignal(false);
return (
<>
<Button onClick={() => setOpen(true)}>Delete</Button>
<Dialog
open={open()}
headline="Delete draft?"
actions={
<>
<Button variant="text" onClick={() => setOpen(false)}>Cancel</Button>
<Button variant="text" onClick={() => setOpen(false)}>Delete</Button>
</>
}
onClose={() => setOpen(false)}
>
<p>The draft will be deleted for good.</p>
</Dialog>
</>
);
}
Refs
ref gives the <m-*> element itself, with its properties and methods, once it is created.
Type it with the element's type from material/elements, and use it in onMount or an event
handler. A callback, ref={(element) => …}, works too.
import { Button, TextField } from 'material/solid';
import type { TextFieldElement } from 'material/elements';
export function Name() {
let field: TextFieldElement | undefined;
return (
<>
<TextField ref={field} label="Name" defaultValue="Ada Lovelace" />
<Button onClick={() => field?.select()}>Select the name</Button>
</>
);
}
Children
A component's children become the element's content: a button's label, a dialog's or a card's
text. A component's named regions, such as a dialog's headline and actions or a top app
bar's leading and trailing, are the element's named slots: pass them as props of those names
taking JSX, as the dialog above does (a dashed slot is camelCased: headerAction). headline
takes text for the attribute or JSX for the slot.
Lists of items are declared with child components: Tab, Radio, Chip, ListItem,
MenuItem, SelectOption, SearchSuggestion, NavigationRailItem, DrawerItem,
ButtonGroupItem and CarouselItem. They render nothing themselves; their parent reads them.
Keep them direct children of their parent, with no element in between. <For> and <Show> are
fine: the parent reads them again when they change.
import { createSignal, For } from 'solid-js';
import { Radios, Radio } from 'material/solid';
const sizes = [{ value: 's', label: 'Small' }, { value: 'm', label: 'Medium' }, { value: 'l', label: 'Large' }];
export function Size() {
const [size, setSize] = createSignal<string | null>('m');
return (
<Radios value={size()} onChange={(event) => setSize(event.detail.value)} ariaLabel="Size">
<For each={sizes}>{(option) => <Radio value={option.value}>{option.label}</Radio>}</For>
</Radios>
);
}
Solid sets a child's props as properties, often before material has defined the elements. material
keeps them from 0.10.0-next.2 on; with an earlier version, a <Tab> rendered in the browser
lost its value.
Bare tags in JSX
To write the elements themselves (<m-switch checked>), with Solid's prop: and on: forms,
import the tag types once, in any file TypeScript sees:
import type {} from 'material/solid/jsx';
export const Wifi = () => <m-switch checked supporting-text="Saves battery">Wi-Fi</m-switch>;
It is types only; the element still needs defineAll() or its define function.
SolidStart and server rendering
The components render on the server. SolidStart's HTML has each element's tag, its attributes
and its children, and a controlled value as its attribute: a switch whose signal is on renders
<m-switch checked>. Every module imports safely without a DOM, and the element registers in
onMount, so it upgrades as the page hydrates. SolidStart adds the hydration script Solid
needs; a hand-made server render puts generateHydrationScript() in the page's head. You don't
need clientOnly for these components, and a ref is only set in the browser.
Until an element upgrades, it has no shadow root and so none of its styles. The pre-upgrade
stylesheet gives each element its final size and look meanwhile, so the page doesn't shift when
the script arrives. Import it once in src/app.tsx:
import 'material/elements/preupgrade.css';
Server rendering explains what the server sends and how the upgrade happens, for every framework.