Common Component Patterns Cheat Sheet

Declaration

import { component$, useStore } from '@builder.io/qwik';

export const Greeter = component$(() => {
  return <span>Hello World!</span>;
});

Props

import { component$, useStore } from '@builder.io/qwik';

interface GreeterProps {
  salutation?: string;
  name?: string;
}
export const Greeter = component$((props: GreeterProps) => {
  const salutation = props.salutation || 'Hello';
  const name = props.name || 'World';
  return (
    <span>
      {salutation} {name}!
    </span>
  );
});

Event Props

Component props must be serializable, and therefore can not directly refer to functions.

import { component$, useStore, PropFunction } from '@builder.io/qwik';

export const Parent = component$(() => {
  return <MyButton doSomething$={() => console.log('Hello')}>click</MyButton>;
});

interface MyButtonProps {
  doSomething$: PropFunction<() => void>;
}
export const MyButton = component$((props: MyButtonProps) => {
  return <button onClick$={props.doSomething$}>click</button>;
});

Events

Watching for Changes

Server

Fetching Data

import { component$, useStore, useServerMount$ } from '@builder.io/qwik';

export const Greeter = component$(() => {
  const store = useStore<{ list: null | string[] }>({ list: null });
  useServerMount$(async () => {
    store.list = await doSomethingToFetchDataOnServer();
  });

  return <ul>{store.list && store.list.map((item) => <li>{item}</li>)}</ul>;
});

Client

Eagerly Executing Code

import { component$, useStore, useClientEffect$ } from '@builder.io/qwik';

export const Greeter = component$(() => {
  const store = useStore<{ list: null | string[] }>({ list: null });
  useClientEffect$(async () => {
    store.list = await doSomethingToFetchDataOnServer();
  });

  return <ul>{store.list && store.list.map((item) => <li>{item}</li>)}</ul>;
});
Made with ♡ by the Builder.io team