Ten minutes to master building a full-stack CRUD application with SolidJS

We could start a discussion  SolidJSsaying it's Reactbetter than , but there's no need to make that comparison. SolidJSJust one of many front-end frameworks designed to Webquickly create data-driven on top of. So, why are we highlighting this new kid?

First, we can't ignore SolidJSnot using virtual DOM. Yes, you heard that right! SolidJS Instead of using a virtual DOM, the entire DOM is remembered from the first run of the application, and then when there is an update, it keeps updating that part. This feature makes the framework very fast and performant.

In this article, we'll show how to build a simple  CRUD application to demonstrate  SolidJS the effectiveness.

Building the SolidJS front end

To build our Solid application we will use  Solid JD Appthe library [https://github.com/OrJDev/create-jd-app]. We'll set up the project, then create and render  SolidJS the component.

Install the Solid JD application library

To get started, run the following commands on the terminal:

npm create jd-app@latest

You'll be prompted to type y (for yes) to continue, and then asked for a name for your app. Next, you will be asked if you will use Vercel to deploy the project. This is a matter of preference. Where you decide to deploy or host your project is entirely up to you; you can even choose None as an option.

The library we use also comes with additional optional add-ons ( AuthJS, Prisma, tRPC, pRPC, TailwindCSS, AuthJSand Upstash Ratelimit). You can decide to select the ones you want or ignore them. In this tutorial we will deploy to Vercel via the dashboard, we will not use any optional add-ons:

Solid JD App Dashboard

After making your selection, click Enter. This will immediately install everything you need, including the node_modules folder containing other packages that SolidJS depends on, as well as any packages you chose during the installation process.

set items

In this tutorial, we'll build a simple blogging application. Move to the root directory of the hosting application and run the following command:

npm run dev

This will start the application on port 3000; http://localhost:3000, where you will see it.

Your code base will look like this; note the use of TypeScript:

SolidJS Codebase Using TypeScript

Here's what you'll see in your browser:

Creating Solid JD App Browser

Next, clean out  src/route/index.tsx the existing code in the file and paste the following: 

import  "../assets/css/style.css";
import { type VoidComponent } from "solid-js";
import { A } from "solid-start";
import Blog from '../components/Blog'
const Home: VoidComponent = () => {
  return (
    <main>
       <div class="container">
          <div class="row g-4">
            <div class="col-lg-8">
              <div class="bg-mode p-4">
                <h1 class="h4 mb-4">Latest blogs</h1>

                </div>
            </div>

          </div>
        </div>
    </main>
  );
};
export default Home;

Create SolidJS components

Components are one of the best things about front-end frameworks, even though the concept of components is not new. Components are just a set of one or more HTML elements, but they make it easier for us to dynamically manage and reuse elements.

Start making components in  a directory src named  components; we'll place any reusable elements and files here. In  components the folder, create a  Blog.jsx file called and paste the following code:

import solidimage from '../assets/images/solid.jpg'
function Blog() {
  return (
    <>
      <div class="card bg-transparent border-0">
        <div class="row g-3">
          <div class="col-4">
            <img class="rounded" src={solidimage} alt="" />
          </div>
          <div class="col-8">
            <a
              href="#"
              class="badge bg-danger bg-opacity-10 text-danger mb-2 fw-bold"
            >
             Tech
            </a>
            <h5>
              <a
                href="blog-details.html"
                class="btn-link stretched-link text-reset fw-bold"
              >
                What is Solidjs? 
              </a>
            </h5>
            <div class="d-none d-sm-inline-block">
              <p class="mb-2">
              SolidJS is an exciting framework for web development that has been gaining traction in recent years. It has been created by Misko Hevery, the creator of Angular. 
.
              </p>
              <a class="small text-secondary" href="#!">
                {" "}
                <i class="bi bi-calendar-date pe-1"></i> Jan 22, 2022
              </a>
            </div>
          </div>
        </div>
      </div>
      <hr class="my-4" />
    </>
  );
}
export default Blog;

You will also need to download the images and  src create subfolders assets/imagesof files within that folder.

Next, assets/csscreate a file in a subfolder  style.css and add this code. In this code  CSS yes  Bootstrap.

Render SolidJS components

You might run into issues, like I did, rendering SolidJScomponents. If so, the easiest solution is  tsconfig.json to add the following to a file located at the root of your project:

"noImplicitAny": false

We'll  render the component src/routeinside a file in the folder  , like so: index.tsx SolidJS

import "../assets/css/style.css";
import { type VoidComponent } from "solid-js";
import { A } from "solid-start";
import Blog from '../components/Blog'
const Home: VoidComponent = () => {
  return (
    <main>
      <div class="container">
        <div class="row g-4">
          <div class="col-lg-8">
            <div class="bg-mode p-4">
              <h1 class="h4 mb-4">Latest blogs</h1>
              <Blog />
              <Blog/>
              <Blog/>
            </div>
          </div>
        </div>
      </div>
    </main>
  );
};
export default Home;

The only difference is that on line 4, we import the Blog component three times. Here's what we now see in a web browser:

SolidJS Component Browser

Create dynamic rendering on the backend

What we just created in the previous section is static data. However, in the real world, the data will come from some kind of backend or API. So, let's make things dynamic!

First, we need to have some kind of endpoint. In this tutorial we will use the following endpoint https://crudcrud.com/api/6a1613c7646f4a908158592cfdb448aa/blog which contains a list of blogs:

picture

To dynamically render data from the API in the Blog component, update Blog.jsxthe file as follows:

import { For, createResource } from "solid-js";
import solidimage from "../assets/images/solid.jpg";
const getBlogs = async () => {
  const response = await fetch(
    "https://crudcrud.com/api/6a1613c7646f4a908158592cfdb448aa/blog"
  );
  return response.json();
};
function Blog() {
  const [blog] = createResource(getBlogs);
  return (
    <Show when={blog()}>
      <For each={blog()}>
        {(eachblog) => (
          <>
            <div class="card bg-transparent border-0">
              <div class="row g-3">
                <div class="col-4">
                  <img class="rounded" src={solidimage} alt="" />
                </div>
                <div class="col-8">
                  <a
                    href="#"
                    class="badge bg-danger bg-opacity-10 text-danger mb-2 fw-bold"
                  >
                    {eachblog.tag}
                  </a>
                  <h5>
                    <a
                      href="blog-details.html"
                      class="btn-link stretched-link text-reset fw-bold"
                    >
                      {eachblog.title}
                    </a>
                  </h5>
                  <div class="d-none d-sm-inline-block">
                    <p class="mb-2">{eachblog.text}</p>
                    <a class="small text-secondary" href="#!">
                      {" "}
                      <i class="bi bi-calendar-date pe-1"></i> Jan 22, 2022
                    </a>
                  </div>
                </div>
              </div>
            </div>
            <hr class="my-4" />
          </>
        )}
      </For>
    </Show>
  );
}
export default Blog;

Here we import the components SolidJSfrom  <For/> . This component is used to traverse the contents of the API (lines 13 and 49).

We also import a  SolidJS CreateResource method. This is used to hold the content of the response (line 10) we  fetch get from the response  JSON (see lines 3-8).

SolidJS Also provides us with another component <Show/>that helps us render things conditionally. The content we use to  <Show/> wrap the entire Blog component.

This  <Show/> component provides a  when() method and this is where we actually define the condition. We specify that  <Show/> the component only renders when there is data or a variable with content (see line 12).

Here's how it looks in the browser:

picture

set routing

Routing refers to how we move from one path of resources to another. Similar to other modern web technologies, SolidJSuse is used Solid Routerto manage how client requests are processed and what to process requests for. Solid state routers are simple and straightforward.

At the time of writing, the package is not installed by default Solid Router. However, we Solid JD Appsetup our project using the library, which includes the router.

To set up the routing, create a new component  BlogDetail.jsx where the blog body will be displayed. Then, paste the following code:

import { useParams } from "@solidjs/router"
import { createResource } from "solid-js"
const getBlog = async (_id) => {
  const response = await fetch('https://crudcrud.com/api/64b773f6659a41b69d678369943f3c5f/blog/' + _id)
  return response.json()
}
export default function BlogDetail() {
  const params = useParams();
  const [blogdetail] = createResource(params._id, getBlog);
  console.log(blogdetail);
  return (
    <div class="my-7">
      <Show when={blogdetail()}>
        <div class="">
          <div class="">
            <h2 class="">{blogdetail.title}</h2>
            <h2>{blogdetail.body}</h2>

          </div>
        </div>tun
      </Show>
    </div>
  )
}

Looking at the API response, you'll notice that there is one  _id unique field; that's what we'll use to locate each piece of content.

In this code, we import  useParams (line 1), which is used to locate a specific parameter from the URL. We then  _id fetch each blog post using its unique as a path parameter and return it as JSON (see lines 3-6).

Next, we export (  BlogDetail lines 13-24) and  params start in a variable (line 8)  useParams() , which is used CreateResource()as a parameter in the method (line 9). Then, we return title and bodythe content of the blog (Lines 11-23).

Now, we need to  src/route/index.tsx define this route in the file. Update the code as follows:

import "../assets/css/style.css";
import { type VoidComponent } from "solid-js";
import { A, Router, Route, Routes } from "@solidjs/router";
import Blog from '../components/Blog';
import BlogDetail from '../components/BlogDetail';

const Home: VoidComponent = () => {
  return (
    <main>
      <div class="container">
        <div class="row g-4">
          <div class="col-lg-8">
            <div class="bg-mode p-4">
              <h1 class="h4 mb-4">Latest blogs</h1>
              <Blog />
            </div>
          </div>
        </div>
      </div>
      <Router>
      <Routes>
        <Route path='/blog/:_id' component={BlogDetail}/>       
      </Routes>
      </Router>
    </main>
  );
};
export default Home;

The change here is that we  solidjs/router import <Router/>the components from the package <Routes/> <Route/>(line 3) and use them to collect data (lines 20-24). If you look closely at line 22, you'll see that we define the try to access blog post path parameter  /blog/_id . Since this has to be dynamic, we pass the component to return BlogDetail.

Summarize

In this article, we successfully demonstrated how to use  SolidJS Build a Blog. You can extend this knowledge to other types of applications. We looked at some  SolidJS methods and components and looked at how they are used in the project.

SolidJS A killer feature of is that it remembers the virtual DOM on first load, and subsequently, different parts will be updated as needed without affecting the entire DOM.

I hope you enjoyed this article. The full codebase of the project can be accessed on GitHub [https://github.com/bigpreshy/solid-crud]. You might also want to look at this deployment: https://solid-crud-ten.vercel.app/.

Guess you like

Origin blog.csdn.net/Z__7Gk/article/details/132167483