Zustand, a minimal store for Rreactjs

In search for a minimal store for React applications.


I have been depending on Context for passing state through components in React and eventually thinks complicated when data is become complex. Move on to beautiful Redux is a bit expensive.

For learning Redux I have spent lots of time and Redux Toolkit, easy to use Redux, saved me a lot.

Even though RTK is ok, it is not a simple library. I am fan of Svelte store and Vuex, Pinia store. Is there any such library for React?

I recently found Zustand a minimal store for React. Love it. 😍

  1. Create a store
  2. Binding
  3. Updating the state

Create a store

Create a store using the create and export the custom hook.

import create from 'zustand'

const useBearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}))

Binding

In your component use the hook. The hook accepts a n arrow functions which will access to the state.

const paw = useBearStore ((state)=>state.bears;

The above statement is Reactive, which means that the changes occurs to the state will reflects. For non reactive purposes us the getState() method.

const paw = useBearStore.getState().bears

Updating the state

For updating the state we can use the setState method.

useBearStore.setState({ bears: 1})

How to use styles in Remix

How to apply CSS styles in Remix


In Reactjs and Nextjs we usually use module bases styles. Remix has its own way for handling style sheets.

links

By defining and expoerting a links funtion in any component, route, Remix will apply those styles to that file. Go head and use those classes.

I gusess that , we can use multipple style sheets since the links functions return an array of style object.

import React from "react";
import styles from "./404.css";
export const links = () => {
  return [
    {
      rel: "stylesheet",
      href: styles,
    },
  ];
};
export default function NF() {
  return (
    <div>
      <div>
        <div>
          <h3>Oops! Page not found</h3>
          <h1>
            <span>4</span>
            <span>0</span>
            <span>4</span>
          </h1>
        </div>
        <h2>we are sorry, but the page you requested was not found</h2>
      </div>
    </div>
  );
}```

Wonder how Links works? In the root(root.jsx) the Links component included so no need to worry about it.

Integrate Hygraph with Svelte, React, Vue

Hygraph headless CMS integration samples


Graph CMS or Hygraph CMS is a headless CMS for building backend for web and mobile apps. It is easy to use.

The Graphql which is modern way to fetch selected part of a database, enable developers to easily access the data in Hygraph.

Integrate Hygraph with Svelte

The first step is to enable public API from the Hygraph settings and then we can use libraries like urql, apollo, graphql-request for querying data.

In the Svelte Kit route we can place a load module on the top of the component for fetching data as follows .

//route/index.svelte

<script context="module">
    import {GraphQLClient} from "graphql-request";
    export async function load({params}) {
        const {slug} = params;
        const graphcms = new GraphQLClient(
            'https://api-ap-south-1.hygraph.com/v2/cl5uo7orr3kf801t8d4ld7hoe/master',
            {
                headers: {},
            }
        )
        const data = await graphcms.request(
            `query  {
        blogpost(where: {slug: "${slug}"})
        {
            title
            catgory
            content{
            html
            }
            publishedAt
            summary
            image {
            fileName
            url
        }
        }
    }`
        );
 return{
     props: {
         post: data.blogpost,
     },
 }
    }

</script>

<script>
    export let post;

</script> 

Similarly we can apply the logic on Angular Service, Vuejs, React, and Solidjs.

I have two projects on Github for you 🎦

How to build a blog using Tailwind + Graphql + Nextjs

Create blog front end using React-Nextjs and Urql – Graphql


We had tried blog with Nuxt 3 and the Solidjs and it is 😎. If you miss the guide here it is.

About the blog and How ?

Let’s build the same blog using Nextjs and the URQL + TailwindCSS. The backend for the app can be from a graphql API , and in this project we used mockend (we can create a mockend Graphql API using mockend and Github )

Here is what we working on .

  • Dynamic route
  • Mockend API
  • Custom 404 component
  • Category Title transition
  • URQL – Graphql client
The complete source code can be found on GitHub , feel free to fork and share.

The Project Structure

The project structure

TailwindCSS

First thing we need to setup is the TailwindCSS which help us to create responsive CSS using the utility classes.

Here is further guide on Tailwind on Nextjs in case require.

Pages

We nee a set of pages and dynamic route for posts and category posts. In Nextjs we can easily setup pages/route under pages directory.

404

The 404 page can be setup as a route that match all, any non existing route/page.

Under the page directory create […].js with default export

import React from 'react'
import PNF from '../Components/PNF'
export default function ErrorPage() {
  return (
    <PNF/>
  )
}
  

Here PNF is beautiful animated PageNotFound component, we just created in the component directory.

Using useRouter/next/router, we can access the params of dynamic route.

Dynamic route

Layout

Our blog uses single layout, so we go with a Layout component which define Navbar and footer and a content area and implement the layout in the _app.js as follows.

//Layout.js

import Nav from './Nav'
export default function Layout({children}) {
    return (
      <>         
        <div className="bg-gray-100">
          <Nav />
          <div className=" items-center overflow-auto h-screen">
           <main> {children}</main>
          </div>
        </div>
      </>
    );
  }

//_app.js
....
function MyApp({ Component, pageProps }) {
  return (
    <Provider value={client}>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </Provider>
  )
}
 

The Layout component saved under the components folder.

Components

We need a set of components to serve in the routes. So lets build it.

The components structure.

I don’t want to pull all the code here.. Here is the code page. Copy and paste it to your components 📂.

Fetching the posts

For querying the data I prefer the URQL library which provides hook for querying data.

Setup Urql

Install the dependency

 yarn add urql graphql 

Also need to configure some next-config

 publicRuntimeConfig: {
    GQL_HOST:'https://mockend.com/manoj-ap/mockbackend/graphql',
    NAV_MENU:[{caption:"Home",path:"/"},{caption:"Blog",path:"/post"},{caption:"Category",path:"/category"},{caption:"About",path:"/About"}],
  } 

You may also note that the NAV_MENU, it is rendered in the Nav component. We can add menu to the list and nav will render it.

Dynamic Menu [nav]

Let’s setup Urql for our project in _app.js using the next-config settings.

import Layout from '../Components/Layout'
import '../styles/globals.css'
import { createClient, Provider } from 'urql';
import getConfig from 'next/config'
const {  publicRuntimeConfig } = getConfig()
const client = createClient({
  url: publicRuntimeConfig.GQL_HOST,
});
function MyApp({ Component, pageProps }) {
  return (
    <Provider value={client}>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </Provider>
  )
}

export default MyApp
 

We wrap the component with Provider so that the entire component tree can use the client.

Querying data

In the index we can query the list of posts as follows

import PostGrid from '../components/PostGrid'
import { useQuery } from 'urql';
import { GridSkelton } from '../Components/Skeltons';
import { useEffect, useState } from 'react';
export default function Home() {
  const query = ` query {
    posts {
      createdAt
      title
      id
      excerpt
      featured_image
    }
  }`;
  
  const [result, reexecuteQuery] = useQuery({
    query: query,
  });
  const { data, fetching, error } = result; 
  return (
    <div  >
              
          {data ? <PostGrid  posts={data.posts}  />:<GridSkelton/> }  
    </div>
  )
}
 

I thing we are almost done. Anything left unclear to 🧒?. Let me know. I will -[…code] 🚀

Lit web components

About Litjs custom web component and Frameworks


Lit is a Javascript library from the house of Google. It is a tiny library and can be a powerful tool for develop reusable web components and apps.

We can create native web component/custom html Tags using Lit with reactivity and other feature mostly offered by libraries like Reactjs.

Also note that it is possible to create custom HTML tags not using any of these libraries, but with a simple Vanilla script.

These libraries simplify our tasks.

Lit web components is compatible with React, Vue or even with HTML pages.

React example

Here is a React Lit example.

Lit Animation

I love making Lit component, do you? 😆

Quilljs mention snippet

React Quilljs mention snippet


We have already covered post regarding Quilljs RichText Editor, configuration and advanced use as well. Now time to get some more feature. This time add some 🥤 to it, the mention.

import React, { Component } from 'react';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import 'quill-mention/dist/quill.mention.css';
import 'quill-mention';
const atValues = [
{ id: 1, value: 'Fredrik Sundqvist' },
{ id: 2, value: 'Patrik Sjölin' },
];
export default class Editor extends Component {
constructor(props) {
super(props);
}
tagModeules = {
toolbar: false,
mention: {
allowedChars: /^[A-Za-z\sÅÄÖåäö]*$/,
mentionDenotationChars: ['@', '#'],
source: function (searchTerm, renderItem, mentionChar) {
let values;
if (mentionChar === '@' || mentionChar === '#') {
values = atValues;
}
if (searchTerm.length === 0) {
renderItem(values, searchTerm);
} else {
const matches = [];
for (let i = 0; i < values.length; i++)
if (
~values[i].value.toLowerCase().indexOf(searchTerm.toLowerCase())
)
matches.push(values[i]);
renderItem(matches, searchTerm);
}
},
},
};
handleProcedureContentChange = (content, delta, source, editor) => {
let has_attribues = delta.ops[1].attributes || "";
console.log(has_attribues);
const cursorPosition = e.quill.getSelection().index;
this.quill.insertText(cursorPosition, "★");
this.quill.setSelection(cursorPosition + 1);
};
render() {
return (
<div class="flex flex-row">
<div>
<label className="" for="tags">
Post Tags
</label>
<ReactQuill
id="tags"
style={{ height: 150 }}
placeholder="#tags here"
modules={this.tagModeules}
>
<div className="my-editing-area" />
</ReactQuill>
</div>
</div>
);
}
}

Here is a live example and try yourself.

react-editor-js double instance fix

How fix double instance issue in react-editor-js block editor toolkit


React-Editor-js is a toolkit for react which implement the Editorjs ,block editor in React application.

The Bugg🐛

When you trying to implement the toolkit into a modern React application you may got double instance of the Editor 👇. I don’t know why it is happening, 😔.

Fix

The problem her is not with the versions but the react-dom/client(🤔). My regular index.js look like this.

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
 
reportWebVitals();

To fix our current issue I replace index.js as following with ReactDom.render method and the problem will melt away. 😊

import ReactDOM from "react-dom";
import React from "react";
import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
 
reportWebVitals();

If anybody have a better solution for this, please leave in the comment section.

React-quill double instance fix

How fix double instance issue in react-quilljs


React-quill is a toolkit for react which implement the Quilljs editor in react application.

When you trying to implement the react-quill into a modern React application you may got double instance of the Editor 👇. I don’t know why it is happening, 😔.

React-quill editor

Fix

The problem her is not with the versions but the react-dom/client(🤔). My regular index.js look like this.

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
 
reportWebVitals();

To fix our current issue I replace index.js as following with ReactDom.render method and the problem will melt away. 😊

import ReactDOM from "react-dom";
import React from "react";
import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
 
reportWebVitals();

If anybody have a better solution for this, please leave in the comment section.

Create minimal editor with Tiptap in React

How to create a minimal editor in React using Tiptap


Tiptap is a modern Editor framework for Javascript applications. It is popular because come with bunch pro features, extension, flexibility and its well documented for all frameworks such as Nextjs, Vuejs, React etc.

There are 50 more extensions ready to boost editor experience.

Let’s setup our react project with Tiptap dependencies.

npx create-react-app tiptapeditor 
npm install @tiptap/core @tiptap/starter-kit @tiptap/react

We can use hooks to create our Tiptap component in React.

import React from 'react'
import { useEditor, EditorContent } from '@tiptap/react'
import Document from '@tiptap/extension-document'
import Paragraph from '@tiptap/extension-paragraph'
import Text from '@tiptap/extension-text'
import './styles.css'

export default function Minimal   ()   {
  const editor = useEditor({
    extensions: [
      Document,
      Paragraph,
      Text,
    ],
    content: `
      <p>
        This is a radically reduced version of tiptap. It has support for a document, with paragraphs and text. That’s it. It’s probably too much for real minimalists though.
      </p>
      <p>
        The paragraph extension is not really required, but you need at least one node. Sure, that node can be something different.
      </p>
    `,
  })

  return (
    <EditorContent editor={editor} />
  )
}

A live example can be found @ Sandbox

Links

Tiptap Repo on Github

Editor frameworks for JS apps

About Javascript Editor frameworks


If you are building content based application such as blog, may want featured editor, such as Post editor or comment box. Making such an editor with all formatting capabilities would be tiresome.

Editor frameworks and wrapper libraries help us achieve this goal with ease and peace. I don’t intended to review each of these , instead I would to list best of them and in the up coming posts we will learn using these awesome editor frameworks.

My Picks

I like block editor mostly for content management, in my react app I will choose the Editor.js . It is easy to configure and use.

Second most useful framework for content management is Drftjs , which is maintained by Facebook itself. It is a complete Editor framework featuring mention, hashtag etc and it’s flexible too.

Here is complete list of framework available for building a full featured editor in your next JS / React/Vue/Angular app