UI developer tutorials and guides

Showing posts with label how to. Show all posts
Showing posts with label how to. Show all posts

Saturday, August 27, 2022

How to use Bootstrap in Svelte apps (using CDN)

 Bootstrap is one of most used CSS/Sass framework nowadays, even though the bundle size is larger than that of TailwindCSS.


 

So how do we use Bootstrap in Svelte and Svelte kit. Importing the CDN link from the entry point would be an ideal approach.

Svelte

In Svelte apps we can use the app.svelte to import the Link and scripts. Svelte provides svelte:head component for including external links or just use a regular head tag.

<svelte:head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
</svelte:head> 

Svelte Kit

In Svelte Kit there is no entry point, so we can use +page.svelte component file for including bootstrap CSS. For global css , +layout.svelte would be the right place. 

Additionally you may require Sass which require configure svelte preprocess. See the Sass guides. πŸ“–

Read More

Configure TailwindCSS in Svelte Kit

 TailwindCSS can be configured in Svelte Kit. Install the dependencies first 🀜.


 

npm install -D tailwindcss postcss autoprefixer svelte-preprocess
npx tailwindcss init tailwind.config.cjs -p 

 Configure the the Tailwind config content key with the following 

//tailwind.config.cjs

content: ['./src/**/*.{html,js,svelte,ts}'], 
Create app.css file and import Tailwind classes and utilities.

//app.css

@tailwind base; @tailwind components; @tailwind utilities;

Import the app.css in +layout.svelte file.

<script> import "../app.css"; </script> <slot /> 
Lets test some style

<h1 class="text-3xl font-bold underline"> Hello world! </h1>

Now it should working. πŸ€”

 Read more TailwindCSS guides


Read More

How to create a component in Svelte

 Components are basic building block in a Svelte app. A Svelte component cane made of simple HTML statements , styles, scripts etc.


Property, Reactivity

There can be only one top level script in a component. Here is a Quick example. 

//src/components/Message.svelte

<script> export let message="Hi";</script>

<h1>{message}<h1>

Property can be defined using a reactive assignment with export state. In Svelte assignment add reactivity. With the special operator $ we can make statements reactive too as follows

<script>
	export let title;

	// this will update `document.title` whenever
	// the `title` prop changes
	$: document.title = title;

	$: {
		console.log(`multiple statements can be combined`);
		console.log(`the current title is ${title}`);
	}
</script>


Read More

Configure Sass in Svelte Kit

 Sass is the most mature, stable, and powerful professional grade CSS extension language. Svelte simplify the use of Sass. 


 

In order to use Sass or scss in Svelte app we have to use the preprocess.

First up all install the node dependencies and sass.

npm i --save-dev bootstrap node-sass svelte-preprocess

In our project locate the  svelte.config.js and import the svelte preprocess and add it to the config object as follows.

import adapter from '@sveltejs/adapter-auto';
import preprocess from 'svelte-preprocess';
/** @type {import('@sveltejs/kit').Config} */

const config = {
kit: {
adapter: adapter()

},
preprocess: [preprocess() ]
};
export default config;

Lets make sure it is working and a simple scss style.

<style lang="scss" type="text/scss" >

$color: red;
h1{
color: $color;
}

</style> <h1>Hello world</h1>

 The heading will be show up in red. πŸ˜†

Read more sass guides

Read More

How to include external CSS and Scripts in Svelte

 One of the problem I was faced in Reactjs and Vue is linking external style sheets and script from CDN which may require special approach.
 


In Svelte we can include the CSS and Script using the dedicated <svelte:head> tag.

<svelte:head>
 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" ...>
</svelte:head>

Sometimes we also need to add external script which provide special functionality to our app, such as bootstrap carousel actions.  drop the script at the head section.

<svelte:head>
 <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" ... crossorigin="anonymous"></script>
</svelte:head>

Svelte also let us import external CSS using the import statement in styles.

@import url("https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css");

Read More

How to create a Svelte app

 Svelte is a Javascript Framework for create web app. We can create a Svelte web app using Svelte Kit. The prerequisites required are


 

  • Nodejs should be installed on development machine
  • Web browser
  • Code editor , (VS Code recommended)

Create a project

 After setting up the Node and npm package manager you can create new project using the following 

npm create svelte@latest my-app
cd my-app
npm install
npm run dev

Routing

Routing is the individual pages in your web app. For more details on routing and all other matters please visit official docs

 

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

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