UI developer tutorials and guides

Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Saturday, August 27, 2022

Svelte, a compiler based Javascript framework

 Svelte is one of the Javascript Frame work , most loved by the developer community. It is little bit different from React, Vuejs and Angular. 

Unlike React Svelte uses a compiler to generate bundles,  as result of this when user launches the app, it run faster, and bundle size will be minimal. πŸš€ 


 

Learning curve

Learning Svelte is not so hard, it is just another language. Documentation is worth reading and there is a good community for help.

Components

Svelte reusable component comprises of plain HTML code. In React they uses functional component or class component with props.

Svelte simplify these. Also let use Markdown to create components and routes. 

Props

Properties props can be think of variable. 

let posts[];

Reactivity

What is achieved in Vuejs' s computed property or React's useEffect can be done with few line of code. Here is how I implemented a search logic in Svelte

 

let searchTerm = '';$: {
if (searchTerm) {
filteredPokemon = $pokemon.filter((pokeman) =>
pokeman.name.toLowerCase().includes(searchTerm.toLowerCase())
);
} else {
filteredPokemon = [...$pokemon];
}

The above code filter pokemons collection using the searchTerm which is a reactive variable and  binded to a input box. Whenever user input search term it will automatically filter and display the content.

The same thing can be done in Reactjs with more lines of code. Thanks to the $ operator which make the reactive property observable.

The complete pokemon project can be found on Github Repo.

SvelteKit

So what is SvelteKit ? It is like Nextjs for React developers. SvelteKit helpful to setup app with all scaffolding and configurations such as routing. In short it is the easiest way to create a Svelte app.

 

Read More

Svelte Kit routing file change

I am surprised to see new routing file system in Svelte Kit, it replaces the routing files such as index.svelte . When you create a Svelte-Kit project, may notice the +page.svelte file, which is the new version of index.svelte.


 

Routes in Svelte-Kit 

So fart we have learned the default route , how about new route, such as about page.  

  • In the src/route folder create about folder
  • Let's create about route component.
  • Every route component should have +page.svelte

In case of fetching data, a  +page.js /+page.ts  will carry the load function. 

Read More

Friday, June 24, 2022

Create a simple store in Solidjs

 Stores are way to distribute collected data among components. In Vuejs Vuex (default) and Pinia stands for stores and for React, you have to choose one like Redux.

Solidjs provides inbuilt store. There are two way to create a store, create a store using createStore method or create a mutable store using createMutable.

A mutable store allow us to directly access and modify data, no need for getters and setters. We goes this way. ➡ 

Create Store

Create a store and export it, so that rest of the modules can access it.

export const store = createMutable({ myText: "" });

 Accessing in component

The component can be accessed and modified using as regular JavaScript objects.

import store from './store'

console.log(store.myText)

Read more about Mutable store


Read More

How to apply refetch logic in Solidjs

 In Reactjs libraries such ReactQuery make API fetching so simple and fast. Solidjs also come with powerful tools. 

We have already seen how to fetch API using the Resource feature. πŸ‘“ 

Sometimes we need to fetch the API again under special circumstances such while network failure,  require to fetch content in a regular intervals etc.

Resource provide us way to re-fetch/ reuse the function. It really do return a re-fetch function and DOM will automatically render the changes after the re-fetch, since it a reactive signal.


const [posts, {refetch}] = createResource(() =>
....
);

How to call the re-fetch and where to call ? πŸ˜‰

One of the ideal use is combine the call with a createEffetct.

In our example we have a search component and want to re fetch particular content based on the search text as the user type in.

createEffect((prev) => {

if (prev !== searchStore.searchString) {
console.log("Search Text changed");
refetch()
}
});

 That's all you need to know about refetch

 

 

Read More

How to set focus to a input in Solidjs

When we required to access the element in the DOM we can use the Ref. It is similar to the Ref in React.

Suppose we have a input text box deeper in the return statement and want to set focus when it rendered, then Ref become handy πŸ–.

Here is the quick example

function Component(){ let myBox;
setTimeout(() => myBox.focus());
return(<> <div> <input ref={myBox} type="text"/></div> </>)}

Here in the Solidjs component example we done the following

  • created a variable myBox
  • Set ref to input box - ref={myBox}
  • Accessing the ref element and set focus to the input.
     


Read More

Wednesday, June 22, 2022

Quickly remove duplicates from array in Javascript

 Suppose we have array with duplicate values. How do we remove then duplicates? I remember Python have simplest way for that and JavaScript have such capabilities too.

let langs=["Vuejs","Angular",Vuejs",Reactjs","Solidjs","Reactjs"];

Here we have duplication values. To remove them, we can looping through each item. There is another way.

Set

Unlike array Sets only store unique values. So lets convert our array to Set with constructor.

const myset= new Set(langs)

 Remember set object will look like the following

{"Angular",Vuejs",Reactjs","Solidjs"}

Back to array

We have to put the values back to array using the spread operator.

langs=[...myset]

Read more JavaScript tips @ JSSU

 

Read More

Tuesday, June 21, 2022

How to setup 404 route in solid-app-router

 404 or commonly known as page not found is must have for any web app. How do we setup the🎭 route and manage the error page ?

Build a beautiful πŸ‘§ error component with 😎 animation.

This example uses solid-app-router , let's setup a router with wild card in App.jsx

<Route path="*" element={() => <PageNotFound />} />

Here the path can be anything which doesn't exists, such as /download , /faq etc and the PageNotFound is just another page component.

When you hit http://localhost:3000/faq the PageNotFound will render if the route is not defined.

Read More

Create a fallback component in Solidjs

 Solidjs offer interesting features that let you conditionally render component. Vuejs and Reactjs didn't offer such a component as I know.

It will be very help full, 😊 When fetching API data and sometimes the data may not retrieve correctly and you can use the <For> component's fallback with an arrow function to render a loading component instead.

Solidjs also provides Show component which help us conditionally render components. The Show component is more applicable in the above mentioned case.

<Show
when={posts()?.length>0}
fallback={() => ( <GridSkelton /> )}>
<For each={posts()}>{(post) => <PostCard post={post} />}</For>
</Show>

Here the Show will check  posts Resource signalπŸ“Ά and make sure the data received properly and then proceed to render it. 

We can also use the fallback in a For component too. 

Read More JavaScript Guides on JavaScript Super User

 

Read More

Saturday, June 18, 2022

Fetch data from graphql API in Solidjs

 I am super excited about the Solidjs, the πŸš€ speed JavaScript framework. In this I will show you how to read data from a

Graphql endpoint. 

There are libraries such as Apollo which used a React specific approach, so I decide to use another library called URQL  

 

How to ?

For reading async data Solidjs provides us Resources, which is a signal. We can combine URQL client within the createResource command with an arrow function.

Install the dependencies

We need two  dependencies for using graphql namely, graphgql and @urql/core

yarn add graphql @urql/core

 

URQL Client

In this example I used a mock graphql API,also  stored the URL in .env (which require vite configuration) file. Let's initialize out API with url

import { createClient } from "@urql/core";
const client = createClient({
url: API_GQL,
});

Create Resource and fetch 

We can either create another function for fetching data as in REST API fetcher or simplify go with an arrow function as follow.

const [posts]= createResource(()=>client.query(`
query {
posts {
title
id
excerpt
featured_image
}
}
`).toPromise().then(data=>{
return data.data.posts
}));

 

 Rendering the data

We can use Show and For components to render the list. Show let's allow check the data is available for render, it may contain null or undefined.

<Show when={posts()}>
<For each={posts()}>{(post) => <PostCard post={post} />}</For>
</Show>

 Read More GQL posts

 

 

 

Read More

Tuesday, June 14, 2022

How to use tailwindcss in Solidjs

 CSS is the most important part of UI development. There are lots of frameworks and libraries such as bootstrap, bulma to make thing easier. Each on has its own use cases.

I prefer using TailwindCSS, it help me to build responsive layout and utility approach save a lot of time and code. 

How do we use tailwindCSS in Solidjs ? We have two options one is use the Tailwind with handy πŸ– features, WindiCSS or go with Latest Tailwind features.

Tailwind   

Configuring Tailwind on Solidjs is similar to Reactjs. We have to go through

  • Install dependencies
  • Generate config and configure content section
  • Integrate classes and components

A detailed guide is here , in case you need them.

WindiCSS

WidniCSS comes with vite configuration, it is make thing easier for Solidjs users. Here is the guide required.

Read More

Dynamic routes and params in Solidjs

 This example based on solid-app-router library. Dynamic routes are those route which are similar to /user/1 /post/79 /tag/tag-name

Note the value 1 and 79 these are used to access particular data from backed. In our case the post with id 79 or user with id 1. These value called parameters.

So how do we setup a dynamic route in Solidjs ?

<Route path='/posts/:id' element={<div>this is a dynamic route </div>}/>

Here we used :id to pass a parameter to the route. In Nuxtjs / Nextjs we used [id].js to deal with dynamic route, in Solidjs we can achieve this in Router definition.

How to access the params ? 

We have to read params from the Route component, it can be arrow function as follows.

import { useParams } from "solid-app-router";
()=>{
const route= useParams()
;}

 Then we can pass the value to the component, the complete Route definition will look like as follows.

<Routes>
<Route path='/' element={Home}/>
<Route path='/posts/:id' element={()=>{
const route= useParams();
return(<SinglePost id={route.id}/>)}}/>
</Routes>

 

Read More

How to use environment variables in Solidjs [vitejs]

 Environment variables can be used in JavaScript application (Nodejs) to store information such API SECRETS. 

Reactjs has inbuilt capacity to consume .env files while Solidjs have to go through vite config..

First up all create .env file at the project root with some information .

API_URI = SOME SECRET

 Configure in vite.config.js

Add a define key ⚿ to the configuration settings as follows in vite.config.js file πŸ“‚.

import { defineConfig, loadEnv } from 'vite'

export default defineConfig(({ command, mode }) => {
const env = loadEnv(mode, process.cwd(), '')
return {
// vite config
define: {
API:JSON.stringify('https://jsonplaceholder.typicode.com/posts'),
APP_ENV: JSON.stringify(env.API_URI)
},
plugins: [solidPlugin()],
build: {
target: 'esnext',
polyfillDynamicImport: false,
},
}
})

Read Official Doc on vite more information β„Ή

 



Read More

How to create global variable in vitejs [Solidjs]

 Vitejs is build tool for modern nodejs applications. Global variable requires in any application where common information need to be accessed in different modules. 

It is common practice is that store values such as URL, KEYS in separate files, in such cases we can use either environment variable or project level symbols.

Read More

Setup windicss for Solidjs

Windicss is the next generation utility CSS framework, for me it is like a simplified tailwind with some jet pack features, it is awesome πŸ˜‚ 


 

Let's configure Windicss for Solidjs project. We are going through following steps.

  • Initialize/create Solidjs a project
  • Install dependencies
  • add vite pluginπŸ”Œ
  • Configure vite config
  • Add windicss to entry point file.

First up all create a new project add all dependecies for Solidjs and windicss.

npx degit solidjs/templates/js my-app yarn install

Let's install vite plugin πŸ”Œ I

Read More