DEV Community

Dhananjay Kumar
Dhananjay Kumar

Posted on

Getting Started with Qwik

Image description

As I write this blog post, Qwik Version 1.1 has been announced. You'll be able to learn about the announcement here.

https://www.builder.io/blog/qwik-v1

Repository – https://github.com/BuilderIO/qwik

This post does not discuss the advantages of the Qwik framework, such as Resumebility, Reactivity, etc., as there are already many discussions on the web. Instead, in this post, directly, you will jump to building and creating a fundamental QWIK app.

Let us jump in. You can just run the commands below on your terminal precisely how you run any CLI commands. You must have NodeJS version 16.8 and above installed to run these commands.

npm create qwik@latest

Qwik will ask you specific questions, such as

  • The app directory name.
  • Project template. (For this Basic App with QWIKCITY)
  • npm library installation option
  • git init option

Provide a name for the app, and then press enter to choose default options. After successful executions of all commands, you should get a message as shown in the below image,

Image description

Next, navigate to the project folder, and you should be able to see the project structure as shown in the following image,

Image description

Open the index.tsx file and replace the code with the below code.

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

export default component$(() => {
  const title = "My First QWIK App";
  return(
    <div>{title}</div>
  )
});
Enter fullscreen mode Exit fullscreen mode

Now run your first QWIK application with the command,

npm run start

It would be best if you got the output as shown in the below image,

Image description

The Qwik works on directory-based routing. In the routes folder, you can see a file called layout.tsx. This file has three sections,

As you might have guessed correctly, the Header and Footer are two components, and in the Slot section on the route change, a component would be projected and lazy loaded.

In the layout file, if you comment and , you should get the output as shown in the following image,

Image description

QWIK uses QWIK CITY, a directory-based routing framework that can download minimal JavaScript with fine-grained lazy loading. Add a new directory in the routes folder to add a new route. You can create various routes by creating different subfolders, as shown below,

src/routes/product

src/routes/product/[id]

src/routes/greet

Inside the product and greet folder, add a file with the name index.tsx, and inside that file, put the below code.

import { component$ } from "@builder.io/qwik";
export default component$(()=>{

    return(
        <h1>Greetings</h1>
    )
})
Enter fullscreen mode Exit fullscreen mode

When you navigate to the – http://127.0.0.1:5173/greet/ , you should get the greet component laded as below,

Image description

When you navigate to the – http://127.0.0.1:5173/product/ , you should get the product component laded as below,

Image description

I will cover Qwik Routing in detail in other posts. However, quickly, you can create a route with a parameter. For example, to create a route with an id parameter, add a subfolder with [id] name inside the product folder and put an index inside that .tsx file.

Image description

You can read the id using the useLocation hook, as shown in the next code listing:

import { component$ } from "@builder.io/qwik";
import { useLocation } from "@builder.io/qwik-city";

export default component$(()=>{

    const loc = useLocation();
    return(
        <h1>{loc.params.id} </h1>
    )
})
Enter fullscreen mode Exit fullscreen mode

When you navigate to – http://127.0.0.1:5173/product/7/, you should get the product component laded as below,

Image description

Another essential task in a web application is fetching data from the API. Qwik makes working with API very easy. To fetch data from API, you can use routeLoader$, which is of type LoaderConstructor.

export const useTodo =  routeLoader$(async ()=>{
    const res = await fetch('https://jsonplaceholder.typicode.com/todos/',{
        headers:{Accept:'application/json'}
    });
    return await res.json()
})
Enter fullscreen mode Exit fullscreen mode

Now you can use custom made useToDo hook in the component as below,

export default component$(()=>{

    const list = useTodo();
    return(
        <>
        <h1>To Do</h1>
        <table>
            <thead>
                <tr>
                <th>Id</th>
                <th>Task</th>
                <th>Status</th>
                </tr>
            </thead>
            <tbody>
            {list.value.map((item:any, index:any) => (
              <tr key={`items-${index}`}> 
                 <td>{item.id} </td>
                 <td> {item.title}</td>
                 <td>{item.completed + ''}</td>
             </tr>
            ))}
            </tbody>
        </table>
        </>
    )
})
Enter fullscreen mode Exit fullscreen mode

Putting everything together in the component, you can fetch data from the API and render it in a table, as shown below:

import { component$ } from "@builder.io/qwik";
import { routeLoader$ } from "@builder.io/qwik-city";

export const useTodo =  routeLoader$(async ()=>{
    const res = await fetch('https://jsonplaceholder.typicode.com/todos/',{
        headers:{Accept:'application/json'}
    });
    return await res.json()
})

export default component$(()=>{

    const list = useTodo();
    return(
        <>
        <h1>To Do</h1>
        <table>
            <thead>
                <tr>
                <th>Id</th>
                <th>Task</th>
                <th>Status</th>
                </tr>
            </thead>
            <tbody>
            {list.value.map((item:any, index:any) => (
              <tr key={`items-${index}`}> 
                 <td>{item.id} </td>
                 <td> {item.title}</td>
                 <td>{item.completed + ''}</td>
             </tr>
            ))}
            </tbody>
        </table>
        </>
    )
})
Enter fullscreen mode Exit fullscreen mode

You can see the data rendered in a table as shown below:

Image description

As with other frameworks, Components are the basic building blocks of Qwik. They are a reusable piece of code. In Qwik, a component is a function that returns a JSX. You can create a component,

  • By adding a folder with the name of the component
  • Inside that, add a file with a name index or component name.
  • Add style with the component.module.css file.

If you wish to create a greet component, add a folder greet; inside that, add an index.tsx or greet.tsx

Image description

In the Greet component, you can apply the CSS from the greet.module.css file as shown in the next code listing:

import { component$ } from "@builder.io/qwik"
import styles from './greet.module.css';

export default component$(() => {

    const title = "Greeting "

    return (
        <>
           <div class={styles['abc']} >{title}</div>
        </>
    )
})
Enter fullscreen mode Exit fullscreen mode

Next, you can use the Greet component on Index as below,

import { component$ } from '@builder.io/qwik';
import Greet from '../components/greet/greet'

export default component$(() => {
  const title = "My First QWIK App";
  return(
    <>
    <div>{title}</div>
    <Greet/>
    </>
  )
});
Enter fullscreen mode Exit fullscreen mode

Some characteristics of Qwik components are,

  • Qwik components get broken down into lazy-loaded chunks
  • Qwik components are resumable
  • Qwik components are reactive

I will cover more about the components and other concepts of QWIK in the following posts. I hope you will like working with QWIK and like this starter post. Thanks for reading it.

Top comments (0)