API › @builder.io/qwik
"q:slot"
'q:slot'?: string;
$
Qwik Optimizer marker function.
Use $(...)
to tell Qwik Optimizer to extract the expression in $(...)
into a lazy-loadable resource referenced by QRL
.
$: <T>(expression: T) => QRL<T>;
AriaAttributes
export interface AriaAttributes
Property | Modifiers | Type | Description |
---|---|---|---|
"aria-activedescendant"? | string | undefined | (Optional) Identifies the currently active element when DOM focus is on a composite widget, textbox, group, or application. | |
"aria-atomic"? | Booleanish | undefined | (Optional) Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute. | |
"aria-autocomplete"? | 'none' | 'inline' | 'list' | 'both' | undefined | (Optional) Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be presented if they are made. | |
"aria-busy"? | Booleanish | undefined | (Optional) Indicates an element is being modified and that assistive technologies MAY want to wait until the modifications are complete before exposing them to the user. | |
"aria-checked"? | boolean | 'false' | 'mixed' | 'true' | undefined | (Optional) Indicates the current "checked" state of checkboxes, radio buttons, and other widgets. | |
"aria-colcount"? | number | undefined | (Optional) Defines the total number of columns in a table, grid, or treegrid. | |
"aria-colindex"? | number | undefined | (Optional) Defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid. | |
"aria-colspan"? | number | undefined | (Optional) Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid. | |
"aria-controls"? | string | undefined | (Optional) Identifies the element (or elements) whose contents or presence are controlled by the current element. | |
"aria-current"? | boolean | 'false' | 'true' | 'page' | 'step' | 'location' | 'date' | 'time' | undefined | (Optional) Indicates the element that represents the current item within a container or set of related elements. | |
"aria-describedby"? | string | undefined | (Optional) Identifies the element (or elements) that describes the object. | |
"aria-details"? | string | undefined | (Optional) Identifies the element that provides a detailed, extended description for the object. | |
"aria-disabled"? | Booleanish | undefined | (Optional) Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable. | |
"aria-dropeffect"? | 'none' | 'copy' | 'execute' | 'link' | 'move' | 'popup' | undefined | (Optional) Indicates what functions can be performed when a dragged object is released on the drop target. | |
"aria-errormessage"? | string | undefined | (Optional) Identifies the element that provides an error message for the object. | |
"aria-expanded"? | Booleanish | undefined | (Optional) Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed. | |
"aria-flowto"? | string | undefined | (Optional) Identifies the next element (or elements) in an alternate reading order of content which, at the user's discretion, allows assistive technology to override the general default of reading in document source order. | |
"aria-grabbed"? | Booleanish | undefined | (Optional) Indicates an element's "grabbed" state in a drag-and-drop operation. | |
"aria-haspopup"? | boolean | 'false' | 'true' | 'menu' | 'listbox' | 'tree' | 'grid' | 'dialog' | undefined | (Optional) Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element. | |
"aria-hidden"? | Booleanish | undefined | (Optional) Indicates whether the element is exposed to an accessibility API. | |
"aria-invalid"? | boolean | 'false' | 'true' | 'grammar' | 'spelling' | undefined | (Optional) Indicates the entered value does not conform to the format expected by the application. | |
"aria-keyshortcuts"? | string | undefined | (Optional) Indicates keyboard shortcuts that an author has implemented to activate or give focus to an element. | |
"aria-label"? | string | undefined | (Optional) Defines a string value that labels the current element. | |
"aria-labelledby"? | string | undefined | (Optional) Identifies the element (or elements) that labels the current element. | |
"aria-level"? | number | undefined | (Optional) Defines the hierarchical level of an element within a structure. | |
"aria-live"? | 'off' | 'assertive' | 'polite' | undefined | (Optional) Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region. | |
"aria-modal"? | Booleanish | undefined | (Optional) Indicates whether an element is modal when displayed. | |
"aria-multiline"? | Booleanish | undefined | (Optional) Indicates whether a text box accepts multiple lines of input or only a single line. | |
"aria-multiselectable"? | Booleanish | undefined | (Optional) Indicates that the user may select more than one item from the current selectable descendants. | |
"aria-orientation"? | 'horizontal' | 'vertical' | undefined | (Optional) Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous. | |
"aria-owns"? | string | undefined | (Optional) Identifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship between DOM elements where the DOM hierarchy cannot be used to represent the relationship. | |
"aria-placeholder"? | string | undefined | (Optional) Defines a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. A hint could be a sample value or a brief description of the expected format. | |
"aria-posinset"? | number | undefined | (Optional) Defines an element's number or position in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. | |
"aria-pressed"? | boolean | 'false' | 'mixed' | 'true' | undefined | (Optional) Indicates the current "pressed" state of toggle buttons. | |
"aria-readonly"? | Booleanish | undefined | (Optional) Indicates that the element is not editable, but is otherwise operable. | |
"aria-relevant"? | 'additions' | 'additions removals' | 'additions text' | 'all' | 'removals' | 'removals additions' | 'removals text' | 'text' | 'text additions' | 'text removals' | undefined | (Optional) Indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. | |
"aria-required"? | Booleanish | undefined | (Optional) Indicates that user input is required on the element before a form may be submitted. | |
"aria-roledescription"? | string | undefined | (Optional) Defines a human-readable, author-localized description for the role of an element. | |
"aria-rowcount"? | number | undefined | (Optional) Defines the total number of rows in a table, grid, or treegrid. | |
"aria-rowindex"? | number | undefined | (Optional) Defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid. | |
"aria-rowspan"? | number | undefined | (Optional) Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid. | |
"aria-selected"? | Booleanish | undefined | (Optional) Indicates the current "selected" state of various widgets. | |
"aria-setsize"? | number | undefined | (Optional) Defines the number of items in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. | |
"aria-sort"? | 'none' | 'ascending' | 'descending' | 'other' | undefined | (Optional) Indicates if items in a table or grid are sorted in ascending or descending order. | |
"aria-valuemax"? | number | undefined | (Optional) Defines the maximum allowed value for a range widget. | |
"aria-valuemin"? | number | undefined | (Optional) Defines the minimum allowed value for a range widget. | |
"aria-valuenow"? | number | undefined | (Optional) Defines the current value for a range widget. | |
"aria-valuetext"? | string | undefined | (Optional) Defines the human readable text alternative of aria-valuenow for a range widget. |
AriaRole
export type AriaRole =
| "alert"
| "alertdialog"
| "application"
| "article"
| "banner"
| "button"
| "cell"
| "checkbox"
| "columnheader"
| "combobox"
| "complementary"
| "contentinfo"
| "definition"
| "dialog"
| "directory"
| "document"
| "feed"
| "figure"
| "form"
| "grid"
| "gridcell"
| "group"
| "heading"
| "img"
| "link"
| "list"
| "listbox"
| "listitem"
| "log"
| "main"
| "marquee"
| "math"
| "menu"
| "menubar"
| "menuitem"
| "menuitemcheckbox"
| "menuitemradio"
| "navigation"
| "none"
| "note"
| "option"
| "presentation"
| "progressbar"
| "radio"
| "radiogroup"
| "region"
| "row"
| "rowgroup"
| "rowheader"
| "scrollbar"
| "search"
| "searchbox"
| "separator"
| "slider"
| "spinbutton"
| "status"
| "switch"
| "tab"
| "table"
| "tablist"
| "tabpanel"
| "term"
| "textbox"
| "timer"
| "toolbar"
| "tooltip"
| "tree"
| "treegrid"
| "treeitem"
| (string & {});
cache
cache(policyOrMilliseconds: number | 'immutable'): void;
Parameter | Type | Description |
---|---|---|
policyOrMilliseconds | number | 'immutable' |
Returns:
void
ClassList
export type ClassList = BaseClassList | BaseClassList[];
cleanup
cleanup(): void;
Returns:
void
Component
Type representing the Qwik component.
Component
is the type returned by invoking component$
.
interface MyComponentProps {
someProp: string;
}
const MyComponent: Component<MyComponentProps> = component$((props: MyComponentProps) => {
return <span>{props.someProp}</span>;
});
export type Component<PROPS extends {}> = FunctionComponent<PublicProps<PROPS>>;
References: FunctionComponent, PublicProps
component$
Declare a Qwik component that can be used to create UI.
Use component$
to declare a Qwik component. A Qwik component is a special kind of component that allows the Qwik framework to lazy load and execute the component independently of other Qwik components as well as lazy load the component's life-cycle hooks and event handlers.
Side note: You can also declare regular (standard JSX) components that will have standard synchronous behavior.
Qwik component is a facade that describes how the component should be used without forcing the implementation of the component to be eagerly loaded. A minimum Qwik definition consists of:
Example
An example showing how to create a counter component:
export interface CounterProps {
initialValue?: number;
step?: number;
}
export const Counter = component$((props: CounterProps) => {
const state = useStore({ count: props.initialValue || 0 });
return (
<div>
<span>{state.count}</span>
<button onClick$={() => (state.count += props.step || 1)}>+</button>
</div>
);
});
component$
is how a component gets declared. -{ value?: number; step?: number }
declares the public (props) interface of the component. -{ count: number }
declares the private (state) interface of the component.
The above can then be used like so:
export const OtherComponent = component$(() => {
return <Counter initialValue={100} />;
});
See also: component
, useCleanup
, onResume
, onPause
, useOn
, useOnDocument
, useOnWindow
, useStyles
component$: <
PROPS = unknown,
ARG extends {} = PROPS extends {} ? PropFunctionProps<PROPS> : {}
>(
onMount: OnRenderFn<ARG>
) => Component<PROPS extends {} ? PROPS : ARG>;
ComponentBaseProps
export interface ComponentBaseProps
Property | Modifiers | Type | Description |
---|---|---|---|
"q:slot"? | string | (Optional) | |
key? | string | number | null | undefined | (Optional) |
componentQrl
Declare a Qwik component that can be used to create UI.
Use component$
to declare a Qwik component. A Qwik component is a special kind of component that allows the Qwik framework to lazy load and execute the component independently of other Qwik components as well as lazy load the component's life-cycle hooks and event handlers.
Side note: You can also declare regular (standard JSX) components that will have standard synchronous behavior.
Qwik component is a facade that describes how the component should be used without forcing the implementation of the component to be eagerly loaded. A minimum Qwik definition consists of:
Example
An example showing how to create a counter component:
export interface CounterProps {
initialValue?: number;
step?: number;
}
export const Counter = component$((props: CounterProps) => {
const state = useStore({ count: props.initialValue || 0 });
return (
<div>
<span>{state.count}</span>
<button onClick$={() => (state.count += props.step || 1)}>+</button>
</div>
);
});
component$
is how a component gets declared. -{ value?: number; step?: number }
declares the public (props) interface of the component. -{ count: number }
declares the private (state) interface of the component.
The above can then be used like so:
export const OtherComponent = component$(() => {
return <Counter initialValue={100} />;
});
See also: component
, useCleanup
, onResume
, onPause
, useOn
, useOnDocument
, useOnWindow
, useStyles
componentQrl: <PROPS extends {}>(componentQrl: QRL<OnRenderFn<PROPS>>) =>
Component<PROPS>;
ContextId
ContextId is a typesafe ID for your context.
Context is a way to pass stores to the child components without prop-drilling.
Use createContextId()
to create a ContextId
. A ContextId
is just a serializable identifier for the context. It is not the context value itself. See useContextProvider()
and useContext()
for the values. Qwik needs a serializable ID for the context so that the it can track context providers and consumers in a way that survives resumability.
Example
// Declare the Context type.
interface TodosStore {
items: string[];
}
// Create a Context ID (no data is saved here.)
// You will use this ID to both create and retrieve the Context.
export const TodosContext = createContextId<TodosStore>("Todos");
// Example of providing context to child components.
export const App = component$(() => {
useContextProvider(
TodosContext,
useStore<TodosStore>({
items: ["Learn Qwik", "Build Qwik app", "Profit"],
})
);
return <Items />;
});
// Example of retrieving the context provided by a parent component.
export const Items = component$(() => {
const todos = useContext(TodosContext);
return (
<ul>
{todos.items.map((item) => (
<li>{item}</li>
))}
</ul>
);
});
export interface ContextId<STATE>
Property | Modifiers | Type | Description |
---|---|---|---|
__brand_context_type__ | readonly | STATE | Design-time property to store type information for the context. |
id | readonly | string | A unique ID for the context. |
CorePlatform
Low-level API for platform abstraction.
Different platforms (browser, node, service workers) may have different ways of handling things such as requestAnimationFrame
and imports. To make Qwik platform-independent Qwik uses the CorePlatform
API to access the platform API.
CorePlatform
also is responsible for importing symbols. The import map is different on the client (browser) then on the server. For this reason, the server has a manifest that is used to map symbols to javascript chunks. The manifest is encapsulated in CorePlatform
, for this reason, the CorePlatform
can't be global as there may be multiple applications running at server concurrently.
This is a low-level API and there should not be a need for you to access this.
export interface CorePlatform
Property | Modifiers | Type | Description |
---|---|---|---|
chunkForSymbol | (symbolName: string, chunk: string | null) => readonly [symbol: string, chunk: string] | undefined | Retrieve chunk name for the symbol.When the application is running on the server the symbols may be imported from different files (as server build is typically a single javascript chunk.) For this reason, it is necessary to convert the chunks from server format to client (browser) format. This is done by looking up symbols (which are globally unique) in the manifest. (Manifest is the mapping of symbols to the client chunk names.) | |
importSymbol | (containerEl: Element | undefined, url: string | URL | undefined | null, symbol: string) => ValueOrPromise<any> | Retrieve a symbol value from QRL.Qwik needs to lazy load data and closures. For this Qwik uses QRLs that are serializable references of resources that are needed. The QRLs contain all the information necessary to retrieved the reference using importSymbol.Why not use import()? Because import() is relative to the current file, and the current file is always the Qwik framework. So QRLs have additional information that allows them to serialize imports relative to application base rather than the Qwik framework file. | |
isServer | boolean | True of running on the server platform. | |
nextTick | (fn: () => any) => Promise<any> | Perform operation on next tick. | |
raf | (fn: () => any) => Promise<any> | Perform operation on next request-animation-frame. |
createContextId
Create a context ID to be used in your application. The name should be written with no spaces.
Context is a way to pass stores to the child components without prop-drilling.
Use createContextId()
to create a ContextId
. A ContextId
is just a serializable identifier for the context. It is not the context value itself. See useContextProvider()
and useContext()
for the values. Qwik needs a serializable ID for the context so that the it can track context providers and consumers in a way that survives resumability.
Example
// Declare the Context type.
interface TodosStore {
items: string[];
}
// Create a Context ID (no data is saved here.)
// You will use this ID to both create and retrieve the Context.
export const TodosContext = createContextId<TodosStore>("Todos");
// Example of providing context to child components.
export const App = component$(() => {
useContextProvider(
TodosContext,
useStore<TodosStore>({
items: ["Learn Qwik", "Build Qwik app", "Profit"],
})
);
return <Items />;
});
// Example of retrieving the context provided by a parent component.
export const Items = component$(() => {
const todos = useContext(TodosContext);
return (
<ul>
{todos.items.map((item) => (
<li>{item}</li>
))}
</ul>
);
});
createContextId: <STATE = unknown>(name: string) => ContextId<STATE>;
DOMAttributes
export interface DOMAttributes<T> extends QwikProps<T>, QwikEvents<T>
Extends: QwikProps<T>, QwikEvents<T>
Property | Modifiers | Type | Description |
---|---|---|---|
children? | JSXChildren | (Optional) | |
key? | string | number | null | undefined | (Optional) |
EagernessOptions
export type EagernessOptions = "visible" | "load" | "idle";
Element
interface Element extends QwikJSX.Element
Extends: QwikJSX.Element
ElementChildrenAttribute
interface ElementChildrenAttribute
Property | Modifiers | Type | Description |
---|---|---|---|
children? | any | (Optional) |
ErrorBoundaryStore
export interface ErrorBoundaryStore
Property | Modifiers | Type | Description |
---|---|---|---|
error | any | undefined |
event$
event$: <T>(first: T) => QRL<T>;
eventQrl
eventQrl: <T>(qrl: QRL<T>) => QRL<T>;
Fragment
Fragment: FunctionComponent<{
children?: any;
key?: string | number | null;
}>;
FunctionComponent
export interface FunctionComponent<P = Record<string, any>>
getCaptured
getCaptured(): any[] | null;
Returns:
any[] | null
getHash
getHash(): string;
Returns:
string
getModifierState
See DOM Level 3 Events spec. for a list of valid (case-sensitive) arguments to this method.
getModifierState(key: string): boolean;
Parameter | Type | Description |
---|---|---|
key | string |
Returns:
boolean
getPlatform
Retrieve the CorePlatform
.
The CorePlatform
is also responsible for retrieving the Manifest, that contains mappings from symbols to javascript import chunks. For this reason, CorePlatform
can't be global, but is specific to the application currently running. On server it is possible that many different applications are running in a single server instance, and for this reason the CorePlatform
is associated with the application document.
getPlatform: () => CorePlatform;
getSymbol
getSymbol(): string;
Returns:
string
h
export declare namespace h
Function | Description |
---|---|
h(type) | |
h(type, data) | |
h(type, text) | |
h(type, children) | |
h(type, data, text) | |
h(type, data, children) | |
h(sel, data, children) |
Namespace | Description |
---|---|
JSX |
h
export declare namespace h
Function | Description |
---|---|
h(type) | |
h(type, data) | |
h(type, text) | |
h(type, children) | |
h(type, data, text) | |
h(type, data, children) | |
h(sel, data, children) |
Namespace | Description |
---|---|
JSX |
HTMLAttributes
export interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T>
Extends: AriaAttributes, DOMAttributes<T>
Property | Modifiers | Type | Description |
---|---|---|---|
about? | string | undefined | (Optional) | |
accessKey? | string | undefined | (Optional) | |
autoCapitalize? | string | undefined | (Optional) | |
autoCorrect? | string | undefined | (Optional) | |
autoSave? | string | undefined | (Optional) | |
color? | string | undefined | (Optional) | |
contentEditable? | 'true' | 'false' | 'inherit' | undefined | (Optional) | |
contextMenu? | string | undefined | (Optional) | |
datatype? | string | undefined | (Optional) | |
dir? | 'ltr' | 'rtl' | 'auto' | undefined | (Optional) | |
draggable? | boolean | undefined | (Optional) | |
hidden? | boolean | 'hidden' | 'until-found' | undefined | (Optional) | |
id? | string | undefined | (Optional) | |
inlist? | any | (Optional) | |
inputMode? | 'none' | 'text' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search' | undefined | (Optional) Hints at the type of data that might be entered by the user while editing the element or its contents | |
is? | string | undefined | (Optional) Specify that a standard HTML element should behave like a defined custom built-in element | |
itemID? | string | undefined | (Optional) | |
itemProp? | string | undefined | (Optional) | |
itemRef? | string | undefined | (Optional) | |
itemScope? | boolean | undefined | (Optional) | |
itemType? | string | undefined | (Optional) | |
lang? | string | undefined | (Optional) | |
placeholder? | string | undefined | (Optional) | |
prefix? | string | undefined | (Optional) | |
property? | string | undefined | (Optional) | |
radioGroup? | string | undefined | (Optional) | |
resource? | string | undefined | (Optional) | |
results? | number | undefined | (Optional) | |
role? | AriaRole | undefined | (Optional) | |
security? | string | undefined | (Optional) | |
slot? | string | undefined | (Optional) | |
spellcheck? | boolean | undefined | (Optional) | |
style? | Record<string, string | number | undefined> | string | undefined | (Optional) | |
tabIndex? | number | undefined | (Optional) | |
title? | string | undefined | (Optional) | |
translate? | 'yes' | 'no' | undefined | (Optional) | |
typeof? | string | undefined | (Optional) | |
unselectable? | 'on' | 'off' | undefined | (Optional) | |
vocab? | string | undefined | (Optional) |
HTMLFragment
HTMLFragment: FunctionComponent<{
dangerouslySetInnerHTML: string;
}>;
implicit$FirstArg
Create a ____$(...)
convenience method from ___(...)
.
It is very common for functions to take a lazy-loadable resource as a first argument. For this reason, the Qwik Optimizer automatically extracts the first argument from any function which ends in $
.
This means that foo$(arg0)
and foo($(arg0))
are equivalent with respect to Qwik Optimizer. The former is just a shorthand for the latter.
For example, these function calls are equivalent:
component$(() => {...})
is same ascomponent($(() => {...}))
export function myApi(callback: QRL<() => void>): void {
// ...
}
export const myApi$ = implicit$FirstArg(myApi);
// type of myApi$: (callback: () => void): void
// can be used as:
myApi$(() => console.log("callback"));
// will be transpiled to:
// FILE: <current file>
myApi(qrl("./chunk-abc.js", "callback"));
// FILE: chunk-abc.js
export const callback = () => console.log("callback");
implicit$FirstArg: <FIRST, REST extends any[], RET>(
fn: (first: QRL<FIRST>, ...rest: REST) => RET
) =>
(first: FIRST, ...rest: REST) =>
RET;
IntrinsicAttributes
interface IntrinsicAttributes extends QwikJSX.IntrinsicAttributes
Extends: QwikJSX.IntrinsicAttributes
IntrinsicElements
interface IntrinsicElements extends QwikJSX.IntrinsicElements
Extends: QwikJSX.IntrinsicElements
jsx
jsx: <T extends string | FunctionComponent<any>>(
type: T,
props: T extends FunctionComponent<infer PROPS> ? PROPS : Record<string, any>,
key?: string | number | null
) => JSXNode<T>;
JSX
namespace JSX
Interface | Description |
---|---|
Element | |
ElementChildrenAttribute | |
IntrinsicAttributes | |
IntrinsicElements |
JSXChildren
export type JSXChildren =
| string
| number
| boolean
| null
| undefined
| Function
| RegExp
| JSXChildren[]
| Promise<JSXChildren>
| Signal<JSXChildren>
| JSXNode;
References: JSXChildren, Signal, JSXNode
jsxDEV
jsxDEV: <T extends string | FunctionComponent<any>>(
type: T,
props: T extends FunctionComponent<infer PROPS> ? PROPS : Record<string, any>,
key: string | number | null | undefined,
_isStatic: boolean,
opts: JsxDevOpts,
_ctx: any
) => JSXNode<T>;
JSXNode
export interface JSXNode<T = string | FunctionComponent>
Property | Modifiers | Type | Description |
---|---|---|---|
children | any | null | ||
dev? | DevJSX | (Optional) | |
flags | number | ||
immutableProps | Record<string, any> | null | ||
key | string | null | ||
props | T extends FunctionComponent<infer B> ? B : Record<string, any> | ||
type | T |
JSXTagName
export type JSXTagName =
| keyof HTMLElementTagNameMap
| Omit<string, keyof HTMLElementTagNameMap>;
NativeAnimationEvent
export type NativeAnimationEvent = AnimationEvent;
NativeClipboardEvent
export type NativeClipboardEvent = ClipboardEvent;
NativeCompositionEvent
export type NativeCompositionEvent = CompositionEvent;
NativeDragEvent
export type NativeDragEvent = DragEvent;
NativeFocusEvent
export type NativeFocusEvent = FocusEvent;
NativeKeyboardEvent
export type NativeKeyboardEvent = KeyboardEvent;
NativeMouseEvent
export type NativeMouseEvent = MouseEvent;
NativePointerEvent
export type NativePointerEvent = PointerEvent;
NativeTouchEvent
export type NativeTouchEvent = TouchEvent;
NativeTransitionEvent
export type NativeTransitionEvent = TransitionEvent;
NativeUIEvent
export type NativeUIEvent = UIEvent;
NativeWheelEvent
export type NativeWheelEvent = WheelEvent;
noSerialize
Marks a property on a store as non-serializable.
At times it is necessary to store values on a store that are non-serializable. Normally this is a runtime error as Store wants to eagerly report when a non-serializable property is assigned to it.
You can use noSerialize()
to mark a value as non-serializable. The value is persisted in the Store but does not survive serialization. The implication is that when your application is resumed, the value of this object will be undefined
. You will be responsible for recovering from this.
See: noSerialize Tutorial
noSerialize: <T extends object | undefined>(input: T) => NoSerialize<T>;
NoSerialize
Marks a property on a store as non-serializable.
At times it is necessary to store values on a store that are non-serializable. Normally this is a runtime error as Store wants to eagerly report when a non-serializable property is assigned to it.
You can use noSerialize()
to mark a value as non-serializable. The value is persisted in the Store but does not survive serialization. The implication is that when your application is resumed, the value of this object will be undefined
. You will be responsible for recovering from this.
See: noSerialize Tutorial
noSerialize: <T extends object | undefined>(input: T) => NoSerialize<T>;
OnRenderFn
export type OnRenderFn<PROPS extends {}> = (
props: PROPS
) => JSXNode<any> | null;
References: JSXNode
OnVisibleTaskOptions
export interface OnVisibleTaskOptions
Property | Modifiers | Type | Description |
---|---|---|---|
strategy? | VisibleTaskStrategy | (Optional) The strategy to use to determine when the "VisibleTask" should first execute.- intersection-observer: the task will first execute when the element is visible in the viewport, under the hood it uses the IntersectionObserver API. - document-ready: the task will first execute when the document is ready, under the hood it uses the document load event. - document-idle: the task will first execute when the document is idle, under the hood it uses the requestIdleCallback API. |
PropFnInterface
export interface PropFnInterface<ARGS extends any[], RET>
PropFunction
export type PropFunction<T extends Function = (...args: any[]) => any> =
T extends (...args: infer ARGS) => infer RET
? PropFnInterface<ARGS, Awaited<RET>>
: never;
References: PropFnInterface
PropFunctionProps
export type PropFunctionProps<PROPS extends {}> = {
[K in keyof PROPS]: NonNullable<PROPS[K]> extends (
...args: infer ARGS
) => infer RET
? PropFnInterface<ARGS, Awaited<RET>>
: PROPS[K];
};
References: PropFnInterface
PropsOf
Infers Props
from the component.
export const OtherComponent = component$(() => {
return $(() => <Counter value={100} />);
});
export type PropsOf<COMP extends Component<any>> = COMP extends Component<
infer PROPS
>
? NonNullable<PROPS>
: never;
References: Component
PublicProps
Extends the defined component PROPS, adding the default ones (children and q:slot)..
export type PublicProps<PROPS extends {}> = TransformProps<PROPS> &
ComponentBaseProps &
ComponentChildren<PROPS>;
References: ComponentBaseProps
qrl
Used by Qwik Optimizer to point to lazy-loaded resources.
This function should be used by the Qwik Optimizer only. The function should not be directly referred to in the source code of the application.
qrl: <T = any>(
chunkOrFn: string | (() => Promise<any>),
symbol: string,
lexicalScopeCapture?: any[],
stackOffset?: number
) => QRL<T>;
QRL
Used by Qwik Optimizer to point to lazy-loaded resources.
This function should be used by the Qwik Optimizer only. The function should not be directly referred to in the source code of the application.
qrl: <T = any>(
chunkOrFn: string | (() => Promise<any>),
symbol: string,
lexicalScopeCapture?: any[],
stackOffset?: number
) => QRL<T>;
QwikAnimationEvent
export interface QwikAnimationEvent<T = Element> extends SyntheticEvent<T, NativeAnimationEvent>
Extends: SyntheticEvent<T, NativeAnimationEvent>
Property | Modifiers | Type | Description |
---|---|---|---|
animationName | string | ||
elapsedTime | number | ||
pseudoElement | string |
QwikChangeEvent
export interface QwikChangeEvent<T = Element> extends SyntheticEvent<T>
Extends: SyntheticEvent<T>
Property | Modifiers | Type | Description |
---|---|---|---|
target | EventTarget & T |
QwikClipboardEvent
export interface QwikClipboardEvent<T = Element> extends SyntheticEvent<T, NativeClipboardEvent>
Extends: SyntheticEvent<T, NativeClipboardEvent>
Property | Modifiers | Type | Description |
---|---|---|---|
clipboardData | DataTransfer |
QwikCompositionEvent
export interface QwikCompositionEvent<T = Element> extends SyntheticEvent<T, NativeCompositionEvent>
Extends: SyntheticEvent<T, NativeCompositionEvent>
Property | Modifiers | Type | Description |
---|---|---|---|
data | string |
QwikDOMAttributes
export interface QwikDOMAttributes extends DOMAttributes<any>
Extends: DOMAttributes<any>
QwikDragEvent
export interface QwikDragEvent<T = Element> extends QwikMouseEvent<T, NativeDragEvent>
Extends: QwikMouseEvent<T, NativeDragEvent>
Property | Modifiers | Type | Description |
---|---|---|---|
dataTransfer | DataTransfer |
QwikFocusEvent
export interface QwikFocusEvent<T = Element> extends SyntheticEvent<T, NativeFocusEvent>
Extends: SyntheticEvent<T, NativeFocusEvent>
Property | Modifiers | Type | Description |
---|---|---|---|
relatedTarget | EventTarget | null | ||
target | EventTarget & T |
QwikIntrinsicElements
The interface holds available attributes of both native DOM elements and custom Qwik elements. An example showing how to define a customizable wrapper component:
import { component$, Slot, type QwikIntrinsicElements } from "@builder.io/qwik";
type WrapperProps = {
attributes?: QwikIntrinsicElements["div"];
};
export default component$<WrapperProps>(({ attributes }) => {
return (
<div {...attributes} class="p-2">
<Slot />
</div>
);
});
export interface QwikIntrinsicElements extends IntrinsicHTMLElements
Extends: IntrinsicHTMLElements
Property | Modifiers | Type | Description |
---|---|---|---|
script | QwikScriptHTMLAttributes<HTMLScriptElement> |
QwikInvalidEvent
export interface QwikInvalidEvent<T = Element> extends SyntheticEvent<T>
Extends: SyntheticEvent<T>
Property | Modifiers | Type | Description |
---|---|---|---|
target | EventTarget & T |
QwikJSX
export declare namespace QwikJSX
Interface | Description |
---|---|
Element | |
ElementChildrenAttribute | |
IntrinsicAttributes | |
IntrinsicElements |
QwikKeyboardEvent
export interface QwikKeyboardEvent<T = Element> extends SyntheticEvent<T, NativeKeyboardEvent>
Extends: SyntheticEvent<T, NativeKeyboardEvent>
Property | Modifiers | Type | Description |
---|---|---|---|
altKey | boolean | ||
charCode | number | ||
ctrlKey | boolean | ||
isComposing | boolean | ||
key | string | See the DOM Level 3 Events spec. for possible values | |
keyCode | number | ||
locale | string | ||
location | number | ||
metaKey | boolean | ||
repeat | boolean | ||
shiftKey | boolean | ||
which | number |
Method | Description |
---|---|
getModifierState(key) | See DOM Level 3 Events spec. for a list of valid (case-sensitive) arguments to this method. |
QwikMouseEvent
export interface QwikMouseEvent<T = Element, E = NativeMouseEvent> extends SyntheticEvent<T, E>
Extends: SyntheticEvent<T, E>
Property | Modifiers | Type | Description |
---|---|---|---|
altKey | boolean | ||
button | number | ||
buttons | number | ||
clientX | number | ||
clientY | number | ||
ctrlKey | boolean | ||
metaKey | boolean | ||
movementX | number | ||
movementY | number | ||
pageX | number | ||
pageY | number | ||
relatedTarget | EventTarget | null | ||
screenX | number | ||
screenY | number | ||
shiftKey | boolean | ||
x | number | ||
y | number |
Method | Description |
---|---|
getModifierState(key) | See DOM Level 3 Events spec. for a list of valid (case-sensitive) arguments to this method. |
QwikPointerEvent
export interface QwikPointerEvent<T = Element> extends QwikMouseEvent<T, NativePointerEvent>
Extends: QwikMouseEvent<T, NativePointerEvent>
Property | Modifiers | Type | Description |
---|---|---|---|
height | number | ||
isPrimary | boolean | ||
pointerId | number | ||
pointerType | 'mouse' | 'pen' | 'touch' | ||
pressure | number | ||
tiltX | number | ||
tiltY | number | ||
width | number |
QwikSubmitEvent
export interface QwikSubmitEvent<T = Element> extends SyntheticEvent<T>
Extends: SyntheticEvent<T>
QwikTouchEvent
export interface QwikTouchEvent<T = Element> extends SyntheticEvent<T, NativeTouchEvent>
Extends: SyntheticEvent<T, NativeTouchEvent>
Property | Modifiers | Type | Description |
---|---|---|---|
altKey | boolean | ||
changedTouches | TouchList | ||
ctrlKey | boolean | ||
metaKey | boolean | ||
shiftKey | boolean | ||
targetTouches | TouchList | ||
touches | TouchList |
Method | Description |
---|---|
getModifierState(key) | See DOM Level 3 Events spec. for a list of valid (case-sensitive) arguments to this method. |
QwikTransitionEvent
export interface QwikTransitionEvent<T = Element> extends SyntheticEvent<T, NativeTransitionEvent>
Extends: SyntheticEvent<T, NativeTransitionEvent>
Property | Modifiers | Type | Description |
---|---|---|---|
elapsedTime | number | ||
propertyName | string | ||
pseudoElement | string |
QwikUIEvent
export interface QwikUIEvent<T = Element> extends SyntheticEvent<T, NativeUIEvent>
Extends: SyntheticEvent<T, NativeUIEvent>
QwikWheelEvent
export interface QwikWheelEvent<T = Element> extends QwikMouseEvent<T, NativeWheelEvent>
Extends: QwikMouseEvent<T, NativeWheelEvent>
render
Render JSX.
Use this method to render JSX. This function does reconciling which means it always tries to reuse what is already in the DOM (rather then destroy and recreate content.) It returns a cleanup function you could use for cleaning up subscriptions.
render: (
parent: Element | Document,
jsxNode: JSXNode | FunctionComponent<any>,
opts?: RenderOptions
) => Promise<RenderResult>;
RenderOnce
RenderOnce: FunctionComponent<{
children?: any;
key?: string | number | null | undefined;
}>;
RenderOptions
export interface RenderOptions
Property | Modifiers | Type | Description |
---|---|---|---|
serverData? | Record<string, any> | (Optional) |
RenderResult
export interface RenderResult
Method | Description |
---|---|
cleanup() |
RenderSSROptions
export interface RenderSSROptions
Property | Modifiers | Type | Description |
---|---|---|---|
base? | string | (Optional) | |
beforeClose? | (contexts: QContext[], containerState: ContainerState, containsDynamic: boolean, textNodes: Map<string, string>) => Promise<JSXNode> | (Optional) | |
beforeContent? | JSXNode<string>[] | (Optional) | |
containerAttributes | Record<string, string> | ||
containerTagName | string | ||
serverData? | Record<string, any> | (Optional) | |
stream | StreamWriter |
resolve
Resolve the QRL and return the actual value.
resolve(): Promise<TYPE>;
Returns:
Promise<TYPE>
Resource
This method works like an async memoized function that runs whenever some tracked value changes and returns some data.
useResource
however returns immediate a ResourceReturn
object that contains the data and a state that indicates if the data is available or not.
The status can be one of the following:
- 'pending' - the data is not yet available. - 'resolved' - the data is available. - 'rejected' - the data is not available due to an error or timeout.
Example
Example showing how useResource
to perform a fetch to request the weather, whenever the input city name changes.
const Cmp = component$(() => {
const store = useStore({
city: "",
});
const weatherResource = useResource$<any>(async ({ track, cleanup }) => {
const cityName = track(() => store.city);
const abortController = new AbortController();
cleanup(() => abortController.abort("cleanup"));
const res = await fetch(`http://weatherdata.com?city=${cityName}`, {
signal: abortController.signal,
});
const data = res.json();
return data;
});
return (
<div>
<input
name="city"
onInput$={(ev: any) => (store.city = ev.target.value)}
/>
<Resource
value={weatherResource}
onResolved={(weather) => {
return <div>Temperature: {weather.temp}</div>;
}}
/>
</div>
);
});
Resource: <T>(props: ResourceProps<T>) => JSXNode;
ResourceCtx
export interface ResourceCtx<T>
Method | Description |
---|---|
cache(policyOrMilliseconds) | |
cleanup(callback) |
ResourceFn
export type ResourceFn<T> = (ctx: ResourceCtx<any>) => ValueOrPromise<T>;
References: ResourceCtx, ValueOrPromise
ResourceOptions
Options to pass to useResource$()
export interface ResourceOptions
Property | Modifiers | Type | Description |
---|---|---|---|
timeout? | number | (Optional) Timeout in milliseconds. If the resource takes more than the specified millisecond, it will timeout. Resulting on a rejected resource. |
ResourcePending
export interface ResourcePending<T>
ResourceProps
export interface ResourceProps<T>
Property | Modifiers | Type | Description |
---|---|---|---|
onPending? | () => JSXNode | (Optional) | |
onRejected? | (reason: any) => JSXNode | (Optional) | |
onResolved | (value: T) => JSXNode | ||
value | readonly | ResourceReturn<T> | Signal<Promise<T> | T> | Promise<T> |
ResourceRejected
export interface ResourceRejected<T>
ResourceResolved
export interface ResourceResolved<T>
ResourceReturn
export type ResourceReturn<T> =
| ResourcePending<T>
| ResourceResolved<T>
| ResourceRejected<T>;
References: ResourcePending, ResourceResolved, ResourceRejected
setPlatform
Sets the CorePlatform
.
This is useful to override the platform in tests to change the behavior of, requestAnimationFrame
, and import resolution.
setPlatform: (plt: CorePlatform) => CorePlatform;
Signal
export interface Signal<T = any>
Property | Modifiers | Type | Description |
---|---|---|---|
value | T |
SkipRender
SkipRender: JSXNode;
Slot
Allows to project the children of the current component. can only be used within the context of a component defined with component$
.
Slot: FunctionComponent<{
name?: string;
}>;
SnapshotListener
export interface SnapshotListener
SnapshotMeta
export type SnapshotMeta = Record<string, SnapshotMetaValue>;
References: SnapshotMetaValue
SnapshotMetaValue
export interface SnapshotMetaValue
Property | Modifiers | Type | Description |
---|---|---|---|
c? | string | (Optional) | |
h? | string | (Optional) | |
s? | string | (Optional) | |
w? | string | (Optional) |
SnapshotResult
export interface SnapshotResult
Property | Modifiers | Type | Description |
---|---|---|---|
funcs | string[] | ||
mode | 'render' | 'listeners' | 'static' | ||
objs | any[] | ||
qrls | QRL[] | ||
resources | ResourceReturnInternal<any>[] | ||
state | SnapshotState |
SnapshotState
export interface SnapshotState
Property | Modifiers | Type | Description |
---|---|---|---|
ctx | SnapshotMeta | ||
objs | any[] | ||
refs | Record<string, string> | ||
subs | any[] |
SSRComment
SSRComment: FunctionComponent<{
data: string;
}>;
SSRHint
Warning: This API is now obsolete.
- It has no effect
SSRHint: FunctionComponent<SSRHintProps>;
SSRHintProps
export interface SSRHintProps
Property | Modifiers | Type | Description |
---|---|---|---|
dynamic? | boolean | (Optional) |
SSRRaw
SSRRaw: FunctionComponent<{
data: string;
}>;
SSRStream
SSRStream: FunctionComponent<SSRStreamProps>;
SSRStreamBlock
SSRStreamBlock: FunctionComponent<{
children?: any;
}>;
SSRStreamProps
export interface SSRStreamProps
Property | Modifiers | Type | Description |
---|---|---|---|
children | AsyncGenerator<JSXChildren, void, any> | ((stream: StreamWriter) => Promise<void>) | (() => AsyncGenerator<JSXChildren, void, any>) |
StreamWriter
export type StreamWriter = {
write: (chunk: string) => void;
};
TaskCtx
export interface TaskCtx
Method | Description |
---|---|
cleanup(callback) |
TaskFn
export type TaskFn = (ctx: TaskCtx) => ValueOrPromise<void | (() => void)>;
References: TaskCtx, ValueOrPromise
Tracker
Used to signal to Qwik which state should be watched for changes.
The Tracker
is passed into the taskFn
of useTask
. It is intended to be used to wrap state objects in a read proxy which signals to Qwik which properties should be watched for changes. A change to any of the properties causes the taskFn
to rerun.
Example
The obs
passed into the taskFn
is used to mark state.count
as a property of interest. Any changes to the state.count
property will cause the taskFn
to rerun.
const Cmp = component$(() => {
const store = useStore({ count: 0, doubleCount: 0 });
useTask$(({ track }) => {
const count = track(() => store.count);
store.doubleCount = 2 * count;
});
return (
<div>
<span>
{store.count} / {store.doubleCount}
</span>
<button onClick$={() => store.count++}>+</button>
</div>
);
});
export interface Tracker
untrack
untrack: <T>(fn: () => T) => T;
useComputed$
useComputed$: Computed;
useComputedQrl
useComputedQrl: ComputedQRL;
useContext
Retrieve Context value.
Use useContext()
to retrieve the value of context in a component. To retrieve a value a parent component needs to invoke useContextProvider()
to assign a value.
Example
// Declare the Context type.
interface TodosStore {
items: string[];
}
// Create a Context ID (no data is saved here.)
// You will use this ID to both create and retrieve the Context.
export const TodosContext = createContextId<TodosStore>("Todos");
// Example of providing context to child components.
export const App = component$(() => {
useContextProvider(
TodosContext,
useStore<TodosStore>({
items: ["Learn Qwik", "Build Qwik app", "Profit"],
})
);
return <Items />;
});
// Example of retrieving the context provided by a parent component.
export const Items = component$(() => {
const todos = useContext(TodosContext);
return (
<ul>
{todos.items.map((item) => (
<li>{item}</li>
))}
</ul>
);
});
useContext: UseContext;
useContextProvider
Assign a value to a Context.
Use useContextProvider()
to assign a value to a context. The assignment happens in the component's function. Once assigned, use useContext()
in any child component to retrieve the value.
Context is a way to pass stores to the child components without prop-drilling.
Example
// Declare the Context type.
interface TodosStore {
items: string[];
}
// Create a Context ID (no data is saved here.)
// You will use this ID to both create and retrieve the Context.
export const TodosContext = createContextId<TodosStore>("Todos");
// Example of providing context to child components.
export const App = component$(() => {
useContextProvider(
TodosContext,
useStore<TodosStore>({
items: ["Learn Qwik", "Build Qwik app", "Profit"],
})
);
return <Items />;
});
// Example of retrieving the context provided by a parent component.
export const Items = component$(() => {
const todos = useContext(TodosContext);
return (
<ul>
{todos.items.map((item) => (
<li>{item}</li>
))}
</ul>
);
});
useContextProvider: <STATE extends object>(context: ContextId<STATE>, newValue: STATE) => void
useErrorBoundary
useErrorBoundary: () => Readonly<ErrorBoundaryStore>;
useId
useId: () => string;
useOn
Register a listener on the current component's host element.
Used to programmatically add event listeners. Useful from custom use*
methods, which do not have access to the JSX. Otherwise, it's adding a JSX listener in the <div>
is a better idea.
useOn: (event: PascalCaseEventLiteralType | PascalCaseEventLiteralType[], eventQrl: QRL<(ev: Event) => void> | undefined) => void
useOnDocument
Register a listener on document
.
Used to programmatically add event listeners. Useful from custom use*
methods, which do not have access to the JSX.
useOnDocument: (event: PascalCaseEventLiteralType | PascalCaseEventLiteralType[], eventQrl: QRL<(ev: Event) => void> | undefined) => void
useOnWindow
Register a listener on window
.
Used to programmatically add event listeners. Useful from custom use*
methods, which do not have access to the JSX.
useOnWindow: (event: PascalCaseEventLiteralType | PascalCaseEventLiteralType[], eventQrl: QRL<(ev: Event) => void> | undefined) => void
useResource$
This method works like an async memoized function that runs whenever some tracked value changes and returns some data.
useResource
however returns immediate a ResourceReturn
object that contains the data and a state that indicates if the data is available or not.
The status can be one of the following:
- 'pending' - the data is not yet available. - 'resolved' - the data is available. - 'rejected' - the data is not available due to an error or timeout.
Example
Example showing how useResource
to perform a fetch to request the weather, whenever the input city name changes.
const Cmp = component$(() => {
const store = useStore({
city: "",
});
const weatherResource = useResource$<any>(async ({ track, cleanup }) => {
const cityName = track(() => store.city);
const abortController = new AbortController();
cleanup(() => abortController.abort("cleanup"));
const res = await fetch(`http://weatherdata.com?city=${cityName}`, {
signal: abortController.signal,
});
const data = res.json();
return data;
});
return (
<div>
<input
name="city"
onInput$={(ev: any) => (store.city = ev.target.value)}
/>
<Resource
value={weatherResource}
onResolved={(weather) => {
return <div>Temperature: {weather.temp}</div>;
}}
/>
</div>
);
});
useResource$: <T>(generatorFn: ResourceFn<T>, opts?: ResourceOptions) =>
ResourceReturn<T>;
useResourceQrl
This method works like an async memoized function that runs whenever some tracked value changes and returns some data.
useResource
however returns immediate a ResourceReturn
object that contains the data and a state that indicates if the data is available or not.
The status can be one of the following:
- 'pending' - the data is not yet available. - 'resolved' - the data is available. - 'rejected' - the data is not available due to an error or timeout.
Example
Example showing how useResource
to perform a fetch to request the weather, whenever the input city name changes.
const Cmp = component$(() => {
const store = useStore({
city: "",
});
const weatherResource = useResource$<any>(async ({ track, cleanup }) => {
const cityName = track(() => store.city);
const abortController = new AbortController();
cleanup(() => abortController.abort("cleanup"));
const res = await fetch(`http://weatherdata.com?city=${cityName}`, {
signal: abortController.signal,
});
const data = res.json();
return data;
});
return (
<div>
<input
name="city"
onInput$={(ev: any) => (store.city = ev.target.value)}
/>
<Resource
value={weatherResource}
onResolved={(weather) => {
return <div>Temperature: {weather.temp}</div>;
}}
/>
</div>
);
});
useResourceQrl: <T>(qrl: QRL<ResourceFn<T>>, opts?: ResourceOptions) =>
ResourceReturn<T>;
useServerData
export declare function useServerData<T>(key: string): T | undefined;
Parameter | Type | Description |
---|---|---|
key | string |
Returns:
T | undefined
useSignal
useSignal: UseSignal;
UseSignal
useSignal: UseSignal;
useStore
Creates an object that Qwik can track across serializations.
Use useStore
to create a state for your application. The returned object is a proxy that has a unique ID. The ID of the object is used in the QRL
s to refer to the store.
Example
Example showing how useStore
is used in Counter example to keep track of the count.
const Stores = component$(() => {
const counter = useCounter(1);
// Reactivity happens even for nested objects and arrays
const userData = useStore({
name: "Manu",
address: {
address: "",
city: "",
},
orgs: [],
});
// useStore() can also accept a function to calculate the initial value
const state = useStore(() => {
return {
value: expensiveInitialValue(),
};
});
return (
<div>
<div>Counter: {counter.value}</div>
<Child userData={userData} state={state} />
</div>
);
});
function useCounter(step: number) {
// Multiple stores can be created in custom hooks for convenience and composability
const counterStore = useStore({
value: 0,
});
useVisibleTask$(() => {
// Only runs in the client
const timer = setInterval(() => {
counterStore.value += step;
}, 500);
return () => {
clearInterval(timer);
};
});
return counterStore;
}
useStore: <STATE extends object>(
initialState: STATE | (() => STATE),
opts?: UseStoreOptions
) => STATE;
UseStoreOptions
export interface UseStoreOptions
Property | Modifiers | Type | Description |
---|---|---|---|
deep? | boolean | (Optional) If true then all nested objects and arrays will be tracked as well. Default is false. | |
reactive? | boolean | (Optional) If false then the object will not be tracked for changes. Default is true. |
useStyles$
A lazy-loadable reference to a component's styles.
Component styles allow Qwik to lazy load the style information for the component only when needed. (And avoid double loading it in case of SSR hydration.)
import styles from "./code-block.css?inline";
export const CmpStyles = component$(() => {
useStyles$(styles);
return <div>Some text</div>;
});
useStyles$: (first: string) => void
useStylesQrl
A lazy-loadable reference to a component's styles.
Component styles allow Qwik to lazy load the style information for the component only when needed. (And avoid double loading it in case of SSR hydration.)
import styles from "./code-block.css?inline";
export const CmpStyles = component$(() => {
useStyles$(styles);
return <div>Some text</div>;
});
useStylesQrl: (styles: QRL<string>) => void
UseStylesScoped
export interface UseStylesScoped
Property | Modifiers | Type | Description |
---|---|---|---|
scopeId | string |
useStylesScoped$
A lazy-loadable reference to a component's styles, that is scoped to the component.
Component styles allow Qwik to lazy load the style information for the component only when needed. (And avoid double loading it in case of SSR hydration.)
import scoped from "./code-block.css?inline";
export const CmpScopedStyles = component$(() => {
useStylesScoped$(scoped);
return <div>Some text</div>;
});
useStylesScoped$: (first: string) => UseStylesScoped;
useStylesScopedQrl
A lazy-loadable reference to a component's styles, that is scoped to the component.
Component styles allow Qwik to lazy load the style information for the component only when needed. (And avoid double loading it in case of SSR hydration.)
import scoped from "./code-block.css?inline";
export const CmpScopedStyles = component$(() => {
useStylesScoped$(scoped);
return <div>Some text</div>;
});
useStylesScopedQrl: (styles: QRL<string>) => UseStylesScoped;
useTask$
Reruns the taskFn
when the observed inputs change.
Use useTask
to observe changes on a set of inputs, and then re-execute the taskFn
when those inputs change.
The taskFn
only executes if the observed inputs change. To observe the inputs, use the obs
function to wrap property reads. This creates subscriptions that will trigger the taskFn
to rerun.
useTask$: (first: TaskFn, opts?: UseTaskOptions | undefined) => void
UseTaskOptions
export interface UseTaskOptions
Property | Modifiers | Type | Description |
---|---|---|---|
eagerness? | EagernessOptions | (Optional) - visible: run the effect when the element is visible. - load: eagerly run the effect when the application resumes. |
useTaskQrl
Reruns the taskFn
when the observed inputs change.
Use useTask
to observe changes on a set of inputs, and then re-execute the taskFn
when those inputs change.
The taskFn
only executes if the observed inputs change. To observe the inputs, use the obs
function to wrap property reads. This creates subscriptions that will trigger the taskFn
to rerun.
useTaskQrl: (qrl: QRL<TaskFn>, opts?: UseTaskOptions) => void
useVisibleTask$
const Timer = component$(() => {
const store = useStore({
count: 0,
});
useVisibleTask$(() => {
// Only runs in the client
const timer = setInterval(() => {
store.count++;
}, 500);
return () => {
clearInterval(timer);
};
});
return <div>{store.count}</div>;
});
useVisibleTask$: (first: TaskFn, opts?: OnVisibleTaskOptions | undefined) => void
useVisibleTaskQrl
const Timer = component$(() => {
const store = useStore({
count: 0,
});
useVisibleTask$(() => {
// Only runs in the client
const timer = setInterval(() => {
store.count++;
}, 500);
return () => {
clearInterval(timer);
};
});
return <div>{store.count}</div>;
});
useVisibleTaskQrl: (qrl: QRL<TaskFn>, opts?: OnVisibleTaskOptions) => void
ValueOrPromise
Type representing a value which is either resolve or a promise.
export type ValueOrPromise<T> = T | Promise<T>;
version
QWIK_VERSION
version: string;
VisibleTaskStrategy
export type VisibleTaskStrategy =
| "intersection-observer"
| "document-ready"
| "document-idle";