Author Archives: Febronei

I can’t install react using npx create-react-app. Here’s the solution

gili lankanfushi

Problem

I was trying to use create-react-app but I got errors which doesn’t allow me to install new react project. The error is shown below:

If you've previously installed create-react-app globally via 
npm install -g create-react-app, we recommend you uninstall 
the package using npm uninstall -g create-react-app or yarn global 
remove create-react-app to ensure that npx

This message could be even stated in the error message you received:

You are running create-react-app 4.0.0, which is behind the 
latest release (4.0.1). We no longer support global installation 
of Create React App.

Solution

You must uninstall create-react-app with npm uninstall -g create-react-app

  1. Uninstall create-react-app v4.0.1
  2. Globally, update npm, clear the cache, and retry creating the app. Use the command below.
npm uninstall -g create-react-app && npm i -g npm@latest && npm cache clean -f && npx create-react-app@latest my-app --use-npm

Note: Some time this command alone will fix the issue.

Different versions of npm may also be helpful, and you may upgrade using the command below. Please keep in mind that this may have an impact on other projects on your system.

Create a Responsive Layout in Flutter

Create a Responsive Layout in Flutter

Flutter is a powerful choice for web and mobile apps development. In Flutter, we can create a fully responsive designs for several platforms using one code base. As we all know a responsive design ensures the appeal of our application is consistent and gives users a seamless experience, no matter the size of the device. For example, when the screen size of the browser extends to a certain width the layout of the app will be changed.

In this short article, we’ll be covering how to create responsive designs in Flutter for web and mobile devices.

Getting Started

To begin, we’ll simply use the app we created in previous tutorial that looks like something like this👇.

💡 For simplicity we are using fixed numbers for screen resolution but when designing user interfaces for mobile apps, always avoid hardcoding numbers for widget sizes and instead utilize percentages. The MediaQuery class in Flutter may be used to do this.

Let’s work on coding…

Make a folder named layout and inside that create new file called layout.dart. Create a stateless widget for now, later we can use a stateful widget when we fetch dynamic contact from backend. We want to return a widget named ResponsiveLayout which helps in creating responsive layout. LayoutBuilder will give us a builder function which then return to us a context and constraints. Using constraints we can get the screen width.

Now create a file named dimensions.dart in the utils folder. Our web screen size starts at 600 resolutions so we will display web layout when the screen size is at 600 and above.

Now we want to create webScreenLayout and mobileScreenLayout widgets and accept these two widgets using a constructor as shown.

class ResponsiveLayout extends StatelessWidget {
  final Widget webScreenLayout;
  final Widget mobileScreenLayout;
  const ResponsiveLayout(
      {Key? key,
      required this.webScreenLayout,
      required this.mobileScreenLayout})
      : super(key: key);

We have accepted those two widgets via a constructor and we want to return those two widgets.

import 'package:flutter/material.dart';
import 'package:flutter_gradient_example/utils/dimensions.dart';

class ResponsiveLayout extends StatelessWidget {
  final Widget webScreenLayout;
  final Widget mobileScreenLayout;
  const ResponsiveLayout(
      {Key? key,
      required this.webScreenLayout,
      required this.mobileScreenLayout})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        if (constraints.maxWidth > webScreenSize) {
          return webScreenLayout;
        }
        return mobileScreenLayout;
      },
    );
  }
}

Now go to main.dart file and replace Center widget with ResponsiveLayout. We then import layout.dart file top of the main.dart file. Then pass both mobileScreenLayout and webScreenLayout as shown below.

It is time to create mobile_screen_layout.dart and web_screen_layout.dart file, so we can use these two widget on main.dart.

import 'package:flutter/material.dart';

class MobileScreenLayout extends StatelessWidget {
  const MobileScreenLayout({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text("This is Mobile Screen"),
      ),
    );
  }
}

We use same stateless widget in both the widget. Make this simple for now by displaying a text on the screen as shown.

import 'package:flutter/material.dart';

class WebScreenLayout extends StatelessWidget {
  const WebScreenLayout({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text("This is Web Screen"),
      ),
    );
  }
}

Now run the app in google Chrome and also in a mobile simulator. So we can test the app. For that run:

flutter run -d chrome

If you want to see it on iOS simulator then run:

open -a simulator

You will notice it is working as expected. When we reduce the chrome screen size to 600 and below it changes to mobile view.

How To Add Your Own Color to a Flutter App

How To Add Your Own Color to Flutter App

Introduction

Learning Flutter is a great idea. Flutter is great if you want to build a career in mobile app development. I’ve planned to write short series based articles on the things I learned about flutter.

In this article, you will explore how to change the overall look across your apps with Flutter themes.


Step 1 — Setting Up the Project

To create a new flutter application simply run the following command. Oh do not forget to complete the installation process of flutter SDK, its prerequisites and the environment setup.


flutter create flutter_custom_theme_example

Flutter create command will give us a demo application that will display a simple clickable button which increment the numbers as we click the button. Now navigate to the new project directory that we just have created.


cd flutter_custom_theme_example

We need to see how our code looks like on the simulators. For that simply run the following code below. We want to enable hot reloading so it reflects the changes as we make to our code.

open -a simulator

Now that you have a working boilerplate Flutter application. It is the time to add customization to the app.



Step 2 — Customize Global Themes

Create a new folder named utils inside lib folder. Create a new file colors.dart inside utils.


import 'package:flutter/material.dart';

const mobileBackgroundColor = Color.fromRGBO(0, 0, 0, 1);
const mobileSearchColor = Color.fromRGBO(38, 38, 38, 1);
const blueColor = Color.fromRGBO(0, 149, 246, 1);
const primaryColor = Colors.white;
const secondaryColor = Colors.grey;

Now we have created a color style globally for our application which can be used anywhere in our app. Open main.dart file and remove all the code given by flutter by default.

We want add dark theme to our app, therefore add dark theme using themeData given by flutter. Next add Scaffold widget to the main.dart file. Now we can see it has changed to default dark color provided by flutter team.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Custom Color Example',
      theme: ThemeData.dark(),
      home: Scaffold(body: Text('Flutter custom color example')),
    );
  }
}

We want a different colors, so this is the point we want to use colors.dart file created earlier so that we can use our own dark theme colors. Import colors.dart file inside our main.dart file. Then add our custom color to themeData shown below code.


import 'package:flutter/material.dart';
import 'package:flutter_custom_theme_example/colors.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Custom Color Example',
      theme: ThemeData.dark().copyWith(
          scaffoldBackgroundColor: mobileBackgroundColor,
          primaryColor: secondaryColor),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter custom color example'),
        ),
        body: Center(
            child: Text(
          'Flutter custom color example',
        )),
      ),
    );
  }
}


Thats it! Now we have added our own custom colors to the flutter app. Yes this is very basic styling however in future tutorial we can add more styles and colors to flutter apps. You can find full code in this Github repo.

How to Create a Gradient AppBar in Flutter

How to Create a Gradient AppBar in Flutter

The gradient color trend is extremely versatile.


Introduction

If you want to feel a different and modern look in your apps then the go for choice is gradient color. The blend of different shades of color, gradient creates a completely unique feelings to the modern designs. Companies such as ,Hulu, Spotify, Airbnb and Laracast often use gradient colors in their products.



This article will teach you how to add and customize these gradient designs into your Flutter app. There are plugins for this to achieve, however we want to implement same exact feature without using any third-party plugins.

So lets begin…


Step 1 — Setting Up the Project

To create a new flutter application simply run the following command. Please make sure to complete the Prerequisites for any flutter project if you are running this command for the first time.


flutter create flutter_gradient_example

Navigate to the project directory you just created:

cd flutter_gradient_example

Step 2 — Using LinearGradient

Open main.dart with your code editor and modify the boilerplate code provide by flutter team. We write most of the our code on this file. We are using simple statelessWidget since there is not state management that we need to take care of.


class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
        // Remove the debug banner
        debugShowCheckedModeBanner: false,
        title: 'Gradient AppBar',
        home: HomePage());
  }
}

In the code below, you will notice we have used Scaffold and AppBar widgets. With these two widgets we are able to create an AppBar on top of our app.

Now use flexibleSpace property, so we can use a Container widget for a gradient layout. There are various kind of gradient but in this case we will use linear gradient method. It is also possible to have additional colors but in this example we are using only red and orange color.


class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // implement the app bar
      appBar: AppBar(
        title: const Text('Gradient AppBar'),
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                colors: [Colors.red, Colors.orange]),
          ),
        ),
      ),
    );
  }
} 

Step 2 — Run the emulator

Compile your code and have it run in an emulator. You will see gradient AppBar on your app.



Thats it. Now you have achieved gradient AppBar in your flutter app. You can find full code in this Github repo.

Step by Step Guide to Install and Set Sanity Cli for Your Next Project

Step by Step Guide to Install and Set Sanity Cli for Your Next Project

Introduction

In this tutorial, you will learn how to get start with Sanity.io for your next project. This tutorial will walk you through installing the necessary tooling, initiating project and starting the local development server for sanity studio. Before that lets understand what sanity.io is all about.


Sanity.io

Sanity.io is the platform for structured content that helps you to build better digital experience. Sanity provides you various features such as managing your text, image and other media files with the help of APIs libraries. Sanity studio offers rapid configuration and free form customization for its users. Using its plugins and toolkits you are able to create efficient workflows. With sanity CMS, now organizing and enhancing your content is easier than ever.



Getting started with Sanity

To begin with simply create a fresh project on your workplace, in this case sanity_backend type the following command on your terminal and let sanity do its thing. Basically this command is going to install a sanity cli globally and sanity init is going to setup a brand new sanity project for you.


npm install -g @sanity/cli && sanity init

The command-line tool is used to set up new projects, manage datasets, import data, and much more. We’ll be using it to get your project up and running.

During the installation process, Sanity wants you to complete a successful login process. It will provide you various login options such as Google, Github and E-mail/Password. Once you complete the login process, it is going to redirect you to Sanity dashboard showing a successful login message on the screen.



Now you can return back to terminal and create a fresh project by providing suitable name for your project. Press enter and you will get dataset configuration setup. You can choose default dataset configuration by pressing Yes and let it create a dataset config for your project.



Once you confirm your path it shows different project templates including blog, E-commerce and movie project.



Sanity provides you a lots of predefined project templates, however in this case we would like to choose a clean project with no predefine schemas.



Write a name for your project on the terminal (in this case sanity_test). Once you press enter, it starts bootstrapping product files and dependencies for your project.



Conclusion

That’s it. Congrats if you made it through the entire tutorial. You’ve just successfully install Sanity CMS to your next project. Sanity is wonderful tool to power your static application such as a blog or e-commerce website.

I hope you find this article helpful. Thank you for reading. Happy Coding..!! 🙂

 

Implement Load More Pagination in React

Implement Load More Pagination in React

Introduction

After Covid-19, Pandemic and now Russia-Ukraine War, so many things happening unexpectedly😔  but thats another story lets focus on our topic for today.

In this article, we will go through how to implement Load more functionality for your next React.js project.

Demo of what we are working on today…👇


Why we need Load more functionality?


For example, you have an e-commerce app and you may need to load products from Rest API or from any other backend database. If we only have 10 or 20 products, it will be easy to fetch them all in just one request. However, if you have hundred and thousands of products sometime even millions, you have to implement pagination to reduce the request hitting on the server. It is important to reduce latency and server load so that the app significantly improves the performance.

So if you want display so many data such as products list, items or blog posts on your web page then you need to implement pagination. For this reason we are learning how to implement basic Load more functionality for in this article. Keep in mind in this example, we will not use any server side rending rather fetch products locally for simplicity.


Steps to implement load more pagination in React

  1. Create a Next.js app
  2. Install TailwindCSS and Configuration
  3. Design the app
  4. Implement load more button functionality
  5. Output

1. Create a Next.js app

Start by creating new Next.js project with TailwindCSS. The quickest way to start using Tailwind CSS in your Next.js project is to use the Next.js + Tailwind CSS Example.


npx create-next-app load-more
cd load-more

2. Install TailwindCSS and Configuration

Install tailwindcssand its peer dependencies via npm, and then run the init command to generate both tailwind.config.js and postcss.config.js.


npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Configure your template paths


module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

Add the Tailwind directives to your CSS

Add the @tailwinddirectives for each of Tailwind’s layers to your ./styles/globals.css file.


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

3. Design the app

Now let’s design the app. We will display list of groceries on the home page. Each product consists of item name, category and image. We will create few components and pages. We start with index.js page. This is main file for our app because it consists of <FreshProd /> component which is responsible to display all the products.


import Head from "next/head";
import Image from "next/image";
import Link from "next/link";
import FreshProd from "../components/FreshProd";

export default function Home() {
  return (
    <main className="container mx-auto px-8 sm:px-12">
      <section className="py-4">
        <div className="flex  items-center justify-between">
          <h2 className="text-md sm:text-2xl font-extrabold py-8">
            Stock Up on Fresh Favorites
          </h2>

          <Link href="/shop">
            <a className="text-base py-8 cursor-pointer text-black">See All</a>
          </Link>
        </div>
        <FreshProd />
      </section>
      <section className="py-4">
        <h2 className="text-2xl font-extrabold py-8">Recommended Products</h2>
        <FreshProd />
      </section>
    </main>
  );
}

As said before we will use all the data locally therefore we left all the data in FreshProd.js component as an object. All the images are also stored in images folder for simplicity. We will fetch data using an external APIs or maybe from firebase database later in another tutorial.


const freshProds = [
  {
    id: "1",
    src: "/images/100p.jpeg",
    name: "100 Plus",
    category: "Groceries",
  },
  {
    id: "2",
    src: "/images/Ajinomoto.jpeg",
    name: "Ajinomoto",
    category: "Groceries",
  },
  {
    id: "3",
    src: "/images/Almondnuts.jpg",
    name: "Almondnuts",
    category: "Groceries",
  }, 
];

Now, store this object in a map so we can display them on <Product /> component. For that we need to Destructuring Props.


function FreshProd() {

  return (
    <div>
      <div className="grid grid-cols-3">
        {freshProds?.map((freshprod) => (
          <Product
            key={freshprod.id}
            src={freshprod.src}
            name={freshprod.name}
            category={freshprod.category}
          />
        ))}
      </div>
    </div>
  );
}

export default FreshProd;

Up to this point, we are able to view all the products in Product component.


import React from "react";

import Image from "next/image";
function Product({ id, name, src, category }) {
  return (
    <div className="py-4">
      <div className="max-w-sm rounded overflow-hidden shadow-lg">
        <Image
          className="rounded-md"
          objectFit="fill"
          src={src}
          width={150}
          height={150}
        />
        <div className="px-6 py-4">
          <div className="font-bold text-xl mb-2">{name}</div>
          <p className="text-gray-700 text-base">{category}</p>
        </div>
      </div>
    </div>
  );
}

export default Product;

Now let’s try to write a function so that it display certain amount of products instead of displaying all the products on the screen. This is where we use Loadmore button and implement pagination on our app. In this case we want to display 6 products.


const [visible, setVisible] = useState(6);

  const showMoreItems = () => {
    setVisible((prevValue) => prevValue + 6);
  };

Lastly we slice the object, so in each time we press the button it will display 6 products on the screen. We use props to pass the data to Product component.


<div className="grid grid-cols-3">
   {freshProds?.slice(0, visible).map((freshprod) => (
      <Product
         key={freshprod.id}
         src={freshprod.src}
         name={freshprod.name}
         category={freshprod.category}
          />
     ))}
</div>

This is the button which is used to load more products on each click.


<div className=" flex flex-col  pt-8	">
    <button
      className=" content-between bg-transparent hover:bg-green-800 
      text-green-800 font-semibold hover:text-white py-2 px-4 border
      border-green-800 hover:border-transparent rounded"
      onClick={showMoreItems} >
          Load More
     </button>
</div>

Wrap Up

Thats it! Now we have implemented simple pagination or loadmore functionlity on our Next.js app project. We can improve this functionality and code but this is a good starting point.


Code

You can find the source code Github

How to Navigate Between Pages Using Next JS Links

How to Navigate Between Pages Using Next JS Links

Introduction


One of the very first reasons to get up early when you’re beachside is to see beautiful sunrise. Today I spent time on beach area aiming to complete this article I started last night. This is a short article where I wrote about Next.js navigation and its implementation. So without further ado let’s jump into the topic.

Websites and web applications generally have more than one pages. But you may wondering, how to achieve routing in Next.js so users able to navigate between the pages. In this article, we’ll explore how to navigate between the pages but before that, first let’s look into the brief introduction of Next.js.


What is Next.js ?


In our previous article we have discussed about Next.js and its cool features in more in-depth. Next.js is an open-source development framework built on top of React.js. It is React based framework having various functionalities to power up both server-side rendering and generating client side static websites.

Next.js gives you amazing developer experience with all the features it provides for any production ready application. Features such as hybrid static & server rendering, TypeScript support, smart bundling, route pre-fetching give developers a seamless development experience.

Now, let’s explore how to add more pages to our application and how to manage page routing in Next.js.


In this article, we will learn:

  • Setup project in Next.js
  • Create pages
  • Use Link component to enable client-side navigation between pages.

1. Setup project in Next.js

We start with initial setup of the Next.js project. If this is the first time you are trying to create a project in Next.js then refer Nextjs official website where you get an extensive knowledge on Nextjs and its core functionalities.

To create a new app simply write the following command create-next-app, which sets up everything automatically for you. To create a project, run:


npx create-next-app@latest
# or
yarn create next-app

After installation is completed:

  • Run npm run dev or yarn dev to start the development server on http://localhost:3000
  • Visit http://localhost:3000 on your browser to view your application

2. Create pages

In Next.js, usually we create separate folder directory called pages. This folder consists of all the pages for the application. Pages are associated with the routes based on their file name. For example:

  • pages/index.js is associated with the / route.

const Index = () => <h1>Home page!</h1>
export default Index;

  • pages/about.js is associated with the /about.js route.

export default function About() {
  return <h1>About</h1>
}

3. Link component

Now we use next/link to enable the redirection between pages. To link different pages, we use <a> HTML tag. Next.js uses Link Component from next/link to wrap the <a> tag. <Link> allows you to do client-side navigation to a different page in the application.


To use Nextjs <Link>

First, open pages/index.js, and import the Link component from next/link by adding this line at the top:


import Link from 'next/link'


export default function Home() {

return (

<div className="lg:inline-flex lg:flex-row lg:ml-auto lg:w-auto w-full 
          lg:items-center items-start  flex flex-col lg:h-auto mr-12">
    <Link href="/">
      <a className="navtext uppercase">Home</a>
    </Link>
    <Link href="/about">
      <a className="navtext uppercase">About</a>
    </Link>
    <Link href="/contact">
      <a className="navtext uppercase"> Contact</a>
    </Link>
</div>

  );
}

In this example we create about us page only for simplicity. Therefore, open pages/about.js  and start writing content. You can add rest of the pages later.


function about() {
  return (
    <div className="container mx-auto px-4 sm:px-12 py-12">
      <h1 className="text-xl font-medium">About</h1>
      <p className="text-md font-base py-12">
        is simply dummy text of the printing and typesetting industry. Lorem
        Ipsum has been the industry's standard dummy text ever since the 1500s,
        when an unknown printer took a galley of type and scrambled it to make a
        type specimen book. It has survived not only five centuries, but also
        the leap into electronic typesetting, remaining essentially unchanged.
        It was popularised in the 1960s with the release of Letraset sheets
        containing Lorem Ipsum passages, and more recently with desktop
        publishing software like Aldus PageMaker including versions of Lorem
        Ipsum.
      </p>
    </div>
  );
}

export default about;

Wrap Up

In this tutorial we learnt how to use Next.js link to navigate between different pages on the websites. Next.js comes with so many great features including Client-Side Navigation and Dynamic Navigation but in this example we have used client-side navigation using Link tag. Now linking pages in any Next.js website is easier than ever, Huge thanks to the Next.js team.

Demo


Full Code

You can get full code from my GitHub repository. Also this demo is deployed in Vercel. Have a look!

Top 11 Best VS Code Extensions you Need in 2022!

Top 11 Best VS Code Extensions you Need in 2022 website

Top Must Have Extensions For Your Next Project

Visual Studio Code is undoubtedly the most popular code editor today. It is lightweight code editor developed by Microsoft for Windows, Linux and macOS. It includes various features such as syntax highlighting, debugging, intelligent code completion, snippets, embedded Git, code refactoring and many more. VS Code provides better performance and stability compared to other code editors in the market.

Microsoft has huge market place for VS Code where developers able to get third party plugins and extensions, availing VS Code more rich and efficient. Today we are discussing top 11 plugins for VS Code which provides invaluable to the speed and quality to your projects.

In this guide, we’ll explore the following extensions.

  1. Git Lens
  2. Peacock
  3. Tailwind CSS IntelliSense
  4. Bracket Pair Colorizer
  5. ES7+ React/Redux/React-Native snippets
  6. Prettier – Code formatter
  7. Auto Rename Tag
  8. Live Share
  9. Vscode-Icons
  10. TODO Highlight
  11. Tabnine AI Autocomplete for Javascript, Python, Typescript, PHP, Go, Java, Ruby & more

1. Git Lens

  • Publishers: GitKraken
  • Installs: 12,650,938 installs
  • Version: 11.7.0, Last Updated 11/18/2021 Free

Overview

GitLens supercharges the Git capabilities. GitLens helps you to understand code better. This powerful and feature rich tool helps to quickly look into code changes such as who, why, and when a line or code block was changed. You are able to find code history to gain further insights as to how and why the code evolved. With this tools, you can effortlessly explore the history and evolution of a codebase.

Here are just some of the unique features GitLens provides,

image visualstudio marketplace
  • Authorship code lens showing the most recent commit and number of authors at the top of files and/or on code blocks
  • status bar blame annotation showing the commit and author who last modified the current line
  • Code changes — highlights any local (unpublished) changes or lines changed by the most recent commit
  • Heatmap — shows how recent and often lines were changed, relative to all the other changes in the file and to now (hot vs. cold)

2. Peacock

  • Publishers: Johnpapa
  • Installs: 1,449,402 installs
  • Version: 4.0.0, Last Updated 11/17/2021 Free

Overview

Developers love to open multiple windows of VS Code as they work on more than one projects at the same time. For example, both backend and front end project could be opened in two separate VS Code instances and developers might want move from one project to another. Using this extension developers able to change the color of each project windows, so that it can be quickly identify which project or repo they are working.

image marketplace.visualstudio

Installation and Configuration

  1. Create/Open a VSCode Workspace (Peacock only works in a Workspace)
  2. Press F1 to open the command palette
  3. Type Peacock
  4. Choose Peacock: Change to a favorite color
  5. Choose one of the pre-defined colors and see how it changes your editor

3. Tailwind CSS IntelliSense

  • Publishers: Tailwind Labs
  • Installs: 871,182 installs
  • Version: 0.7.6, Last Updated 01/17/2022 Free

Overview

TailwindCSS is a utility-first CSS framework that has been gaining huge attention among the web developers. If you love Tailwind CSS then this is a must have extension to have. It is a free extension, published by Tailwind Labs (bradlc). This extension provides autocomplete, syntax highlighting, and linting for Tailwind classes. With this extension, developers don’t need to memorize the exact spelling of all the utility classes or to spend the time typing them out.

Linting

Linting highlights errors and potential bugs in both your CSS and your markup. It is the process of checking the source code for Programmatic as well as Stylistic errors.

Autocomplete

Intelligent suggestions for class names, as well as CSS functions and directives.

Installation and Configuration

In order for the extension to activate you must have tailwindcss installed and a Tailwind config file named tailwind.config.js or tailwind.config.cjs in your workspace.


4. Bracket Pair Colorizer

  • Publishers: CoenraadS
  • Installs: 7,279,363 installs
  • Version: 1.0.62, Last Updated 12/13/2021 Free

Overview

As our functions get more complex, it becomes more challenging to keep track of opening and closing brackets such as parentheses and curly braces.

We can use a VS Code extension called Bracket Pair Colorizer to add color to each set of opening and closing brackets, making it easier to identify each set of brackets.

image dev.to

Installation and Configuration

Install Bracket Pair Colorizer latest version from VS code package. After installation if you want customization:

  • Open up Settings by clicking Code > Preferences > Settings.
  • Search colorizer
  • Click Edit in settings.json beneath the bracket-pair-colorizer: Colors.

5. ES7+ React/Redux/React-Native snippets

  • Publishers: dsznajder
  • Installs: 4,344,921 installs
  • Version: 4.1.0, Last Updated 1/20/2022 Free

Overview

If you are a true React JS developer then this is a must have snippet for you, because it simply does just right for you. This plugin provides you JavaScript and React/Redux snippets in ES7 with Babel plugin features for VS Code.

image geeksforgeeks

Here you can see couple of popular PrefixMethod example for React developers, and the full list can be seen from official Github page.

To make a new class component, simply run:

rcc→

rce→

rfce

To make a functional component, simply run:

import React from 'react';

function $1() {
  return <div>$0</div>;
}

export default $1;

Installation and Configuration

Launch Quick Open:

Paste the following command and press Enter:

ext install dsznajder.es7-react-js-snippets

6. Prettier – Code formatter

  • Publishers: Prettier
  • Installs: 18,020,985 installs
  • Version: 9.1.0, Last Updated 1/3/2022 Free

Overview

Developers have different opinions on how to format the code structure so it would be readable. Prettier was created as a means of alleviating this challenge and ensures one unified code format within the development team.

Prettier reformats your JavaScript code consistently so that it make easy to read and understand the code. This plugin helps to format spacing, variable declarations, semi-colons, trailing commas and much more.

You can configure Prettier to format your files when saving them or committing them to a version control system (e.g. Git, SVN). This way, you do not have to worry about your source code formatting and Prettier takes care about it.

image honeypot

Installation and Configuration

Install through VS Code extensions. Search for Prettier - Code formatter

Visual Studio Code Market Place: Prettier – Code formatter

You can also installed in VS Code: Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.

ext install esbenp.prettier-vscode

7. Auto Rename Tag

  • Publishers: Jun Han
  • Installs: 7,766,922 installs
  • Version: 0.1.9, Last Updated 10/12/2021 Free

Overview

Most of the tags in HTML/XML need a corresponding closing tag. When writing large applications which consists of thousands and sometime millions of lines of code, the corresponding closing tags might located at very bottom of the editor, where developers has to scroll hundreds and thousand of lines below. It is tedious if you want to rename the tags.

Auto Rename Tag provides us with a feature that when we change the starting tag it will automatically rename paired HTML/XML tag, same as Visual Studio IDE does, making the renaming of tags easier.

Installation and Configuration

You can simply install the plugin using VS code Extensions. After installation, Add entry into auto-rename-tag.activationOnLanguage to set the languages that the extension will be activated. By default, it is [“*”] and will be activated for all languages.

{
  "auto-rename-tag.activationOnLanguage": ["html", "xml", "php", "javascript"]
}

8. Live Share

  • Publishers: Microsoft
  • Installs: 7,397,050 installs
  • Version: 1.0.5273, Last Updated 1/20/2022 Free

Another great contribution by Microsoft. Live Share enables you to collaboratively edit and debug code with other developers in real time. Using this tools, pair programming has become more convenient, where developers can instantly and securely share the project with other developers.

Common features it includes, debugging sessionsterminal instanceslocalhost web appsvoice calls, and more!

It shares all of their editor context meaning, other developers do not worry about cloning any repos or SDKs installation for code review and debugging process.

Installation and Configuration

  1. If needed, install Visual Studio Code for Windows (7+), macOS (Sierra+), or Linux (details).
  2. Download and install the Visual Studio Live Share extension for Visual Studio Code.
    If you want to integrated voice calling, then install the VS Live Share Extension Pack, which includes both the Live Share and Live Share Audio extensions.
  3. Let Visual Studio Live Share to finish installing dependencies.
  4. Once complete, you’ll see Live Share appear in your status bar. You can now begin collaborating with others immediately!

Quickstart (Joining)

  1. Click the session URL the “host” sent you, which will open it up in a browser. When prompted, allow your browser to launch VS Code
  2. You’ll be asked to sign in the first time you share (using a GitHub or Microsoft account), which allows others to identity you when collaborating.
  3. That’s it! After you join, you’ll be immediately presented with the file that the “host” has open, and can see their cursor and any edits they make. Additionally, you start out “following” the host, so as they scroll or navigate between files, you’ll follow along with them. This makes it easy to orient yourself with the issue/question/task you’re about to start collaborating on.

9. Vscode-Icons

  • Publishers: VSCode Icons Team
  • Installs: 9,823,196 installs
  • Version: 11.8.0, Last Updated 12/4/2021 Free

Overview

Having descriptive icons help you differentiate between files and folders in the project. Having icons in your project make more interesting and attractive. Below diagram depict different between two VS Code tabs with One having icons, the other does not.

image logrocket

Installation and Configuration

To install the extension just execute the following command in the Command Palette of Visual Studio Code:

ext install vscode-icons

Once installed and after reloading vscode, you will be presented with a message to Activate the icons.

In case this doesn’t happen, navigate to:

  • Linux & Windows => File > Preferences > File Icon Theme > VSCode Icons.
  • MacOS => Code > Preferences > File Icon Theme > VSCode Icons.

10. TODO Highlight

  • Publishers: Wayou Liu
  • Installs: 2,270,992 installs
  • Version: 11.8.0, Last Updated 12/4/2021 Free

This plugin lets you to highlight TODO, FIXME and other annotations within your code. This is really a useful plugin for highlighting comments such as NOTE: , TODO: , DEBUG:. The customization settings are also quite extensive making it perfect for the developer, thus leading level up your comments on any project.

image visualstudio marketplace

Installation and Configuration

  • TODO:,FIXME: are built-in keywords.
  • You can override the look by customizing the setting.
  • To customize the keywords and other stuff,
  • command + ,
  • (Windows / Linux: File -> Preferences -> User Settings)
  • open the vscode file settings.json.

11. Tabnine AI Autocomplete for Javascript, Python, Typescript, PHP, Go, Java, Ruby & more

  • Publishers: TabNine
  • Installs: 3,112,708 installs
  • Version: 3.5.16, Last Updated 1/12/2022 Free

Overview

Tabnine is the AI code completion assistant already trusted by millions of developers to amplify coding accuracy and boost productivity. Whether you are a new dev or a seasoned pro, working solo or part of a team, Tabnine AI assistant will suggest team-tailored code completions in most popular coding languages and all your favorite IDEs.

Tabnine is powered by sophisticated machine learning models. It is trained on more than a billion lines of open-source code from GitHub.

Tabnine suggests and predicts code as you write. This powerful extension speed up your development, save you tons of time and cutting your coding time in half. Currently it support almost all the popular programming languages including Python, Javascript, Java and React.

Tabnine’s Team Learning Algorithm studies your team’s code, preferences, and patterns, continuously learning and adapting. Every interaction with a team member amplifies code completion accuracy.

Installation and Configuration

  • Press Cmd+P (mac) or Ctrl+P (Windows) in your Visual Studio Code, type ext install Tabnine.tabnine-vscode and press Enter
  • Click the Reload button in the extensions tab
  • The default behavior of Tabnine uses the Enter key to accept completions. If you would rather use the Enter key to start a new line, go to Settings → Editor: Accept Suggestion On Enter and turn it off.

Conclusion

In this article, we reviewed 11 VS Code extensions that can help to make you a better programmer and boost your productivity. There are many more other cool extensions that we need to explore in future, so If we have time then will definitely look into those extensions in the coming articles.

Why You Want to Choose Next.js for Your Next Projects in 2022


5 Killer game-changing features in Next.js 12.


It was a while ago when the newest version of Next.js has released. Today we will look into the features that came with Next.js 12. But before that, first let me tell you something about of Next.js.


Introduction


Next.js is an open-source development framework built on top of React.js. It is React based framework which have various functionalities to power up both server-side rendering and generating client side static websites.

Next.js gives you the best developer experience with all the features it present for any production ready apps. Features such as hybrid static & server rendering, TypeScript support, smart bundling, route pre-fetching give developers a seamless development experience. Here are its newest features available in the latest version of its release:

So what are the game changing features available in the recent release.


Middleware


Middleware is not a new concept. Frameworks such as Express.js and Laravel use middleware to intercept http requests and process in someway before it goes to actual route handler.

This is one of the most exciting features in this release. Why this version is special and exciting?

You want your website to be fast and efficient. The best way to make it happened is to cache pre-built html pages on a CDN. But when you do that you lose ability to make your pages dynamic.

On the other side, you have server side rendering that uses a node server to fetch data from a database or an api when when the incoming request comes in. The problem in that is, it is slow and inefficient. In a perfect world users need speed and dynamic content at the same time.

Next.js has very clever approach, leading the way to achieve both at the same time. Vercel, the parent company of Next.js has a product called edge function feature. These are serverless functions like AWS lambda or Google Cloud function except they are deployed to the edge like CDN so your end users get extremely fast executions.

Common use cases for where we can use middleware are?

  • User Authentication
  • Bot protection
  • Redirects and rewrites
  • Handling unsupported browsers
  • Service-side analytics
  • Logging

Concurrent Mode


Concurrent Mode helps React apps stay responsive. It gracefully adjust to the user’s device capabilities and network speed. React 18 adds new features including, Suspense, automatic batching of updates, APIs like startTransition, and a new streaming API for server rendering with support for React.lazy.

If you are not familiar with suspense it is basically a component that allows you to wait asynchronous data before rending its children. In previous version of Next.js if we use this suspense component it would result an error as it is not compatible with previous versions. In Next.js 12 it supports this feature and we get ability to implement it by enabling SSR Streaming.

To enable concurrent mode, Ensure you have the rc npm tag of React installed first then use the experimental flag concurrentFeatures: true::


npm install next@latest react@rc react-dom@rc

// next.config.js
module.exports = {
  experimental: {
    concurrentFeatures: true,
  },
}

Server Components


React Server Components render everything, including the components themselves, on the server. This is fundamentally different from server-side rendering where you’re pre-generating HTML on the server. With Server Components, there’s zero client-side JavaScript needed, making page rendering faster.

Server components allow you to natively render html from a react component on the server. It uses http streaming to progressively render a web page on the server. That means if you need data for one component and then another component and another, you don’t have to wait for one after the other. It will render the first one, the next one and so on.

With server components you can stream html from an edge function immediately and progressively show update as your data comes in. This improves the user experience of your application, pairing the best parts of server-rendering with client-side interactivity.

How to Enable React Server Components

To use React Server Components, ensure you have React 18 installed. Then, turn on the concurrentFeatures and serverComponents options in next.config.js:


// next.config.js
module.exports = {
  experimental: {
    concurrentFeatures: true,
    serverComponents: true,
  },
}

Next, if you already have customized pages/_document component, you need to remove the getInitialProps static method and the getServerSideProps export if there’s any, otherwise it won’t work with server components. If no custom Document component is provided, Next.js will fallback to a default one like below.


// pages/_document.js
import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html>
      <Head />
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

URL Imports


URL imports is now available in the newest version. Next.js team has been experimenting this services for a while to make sure it fully supports ES Modules in the previous version.

This feature is nice to have as we can now import open source packages directly from the CDN without any extra builds or installs. We will be able to import required packages from CDN rather than having to build them locally. Therefore, now we can use popular CDN source such as Skypack in your Next.js app.

The major benefit of using package over CDN is, they speeds up any website instantly using optimized JavaScript hosting services. The production-ready CDN is powered by Google Cloud, Cloudflare and AWS. It creates ready-for-production tools without the hassle of compiling and bundling them seamlessly. It scans NPM and builds executable ES module packages that you can import from your Browser.

To enable this feature? The URL has to be specified in the next.config.js file. You need to only enable domains that you trust.


module.exports = {
  experimental: {
    urlImports: ['https://cdn.skypack.dev'],
  },
}

Collaborative Live Coding


Working from home is increasingly common these days. Even before COVID-19, remote job was a popular trend. The shift means that you need more collaborative tools to work better as a team. With Next.js 12 this is taken to the next level. Now we are able to code, share, draw and edit instantly within your Browser using vercel platform. Your application will be hosted in Vercel.com and integrated through your chosen git vendor. After the deployment process, vercel provides you a live URL within seconds and kick off a pair programming session.

The most relevant features are:

  • In-browser editing
  • Invite any team member
  • Only your favorite browser is required
// Vercel collaborative feature URL
https://vercel.com/live  

Wrap Up


In a nutshell, Next 12 is a complete game changer since it’s focused on development friendliness and performance in mind.

With Next.js 12, overall development workflows will be improved. It creates more possibilities for your web projects. By improving existing processes and functionalities, and adding new features to the framework, frontend developers now have more tools to create better user experiences in an efficient way.

As of now some of the awesome features are not stable, however we can still use those features in our application as we await a stable release of React 18.

Flutter or React Native – Which Technology to Choose in 2022

Building high quality cross-platform mobile app is extremely difficult technical challenge. If you are building a cross-platform mobile application, there are two popular option to choose.

They are React Native from Facebook and Flutter from Google. These two frameworks are mature enough to achieve same fundamental goals, builds apps for multi platforms such as iOS, Android and the Web from a single code base.

In this tutorial we look into the detailed side-by-side comparison of these two popular technology. The key areas we look in this tutorial are:

  • Features
  • Tooling
  • Developer experience
  • Performance
  • The code structure

Let’s start by comparing the programming languages that have been used in these two frameworks.

Programming Language

React Native

In React Native we code apps in Javascript. Basically React Native is just an extension of Javascript language. It also support TypeScript incase if you want add type system on top of the Javascript.

Flutter

Dart is the programming language used in Flutter. Dart is a client-optimized language which helps quickly develop apps on any platform. Flutter runs in the Dart virtual machine, which features just-in-time execution engine. Flutter apps are compiled with ahead-of-time (AOT) compilation therefore it has a better performance.

Ecosystem

Now let’s look at the ecosystem of both these frameworks. According to recent Github stats, these two frameworks have the most active repositories as of 2021.

Development Philosophy

A complete React Native project basically needs bunch of third party plugins and dependencies, however React Native comes with minimal bare bone architecture. In most of cases the open source community develop and maintain the those plugins and dependencies for React Native apps.

Flutter on the other hand comes with huge set of widget library. It consists of large number of plugins and packages developed by flutter team. Dart also has package manager called pub and there is huge ecosystem of open source packages for flutter as well.

Architecture

Now let’s discuss the underlying architecture of these two technologies. First, how React Native works?

Under the hood React Native runs two separate javascript threads. One is the main thread to run the app on whatever native platform and the other is a thread to run the business logic of your application. These threads are isolated from each other but sometimes they need to interact so there is a bridge in the middle where they can pass serialized messages back and forth.

Because of this architectural design, it allows Javascript to communicate with native platform. When React Native renders a component it is a truly native component on the corresponding platform. It is not just a react website bundled as a mobile app but it’s truly rendering native components. That means the user interface of the application looks exactly like native components.

Instead of rendering native UI components, Flutter has its own high performance rendering engine built with C++ and Skia graphics library that renders its own custom pixel to the screen with compile native code that allows it to render pixel perfect versions of iOS and Android widgets while also making it to possible to paint your own custom pixels to the screen.

Developer Experience

Now we look into the developer experience for both technologies. Starting with initial setup, for React Native we can generate new app by running the following command.

npx react-native init MyApp --template react-native-template-typescript@next

After installing SDK for flutter, we can run the following command to create a flutter project.

flutter create my_app

You might have noticed, creating a flutter project is considerably faster, because it doesn’t reached out to npm to download bunch of npm packages. In flutter project we can find pubspec.yaml file instead of package.json. Pubspec.yaml file is used to register and install all the necessary packages for the application.

Project structure for flutter is more simplified when compared to React Native project. The main config file for flutter is pubspec.yaml while in React Native is package.json file.

Tooling

Now we can look into the common tools used in each technology. Having a really good tool set is important when we develop cross-platform mobile apps because without good tooling development life cycle will be miserable. It is possible to run mobile apps locally using emulators to see changes we make during development phase.

To run a React Native app locally we need to follow these steps. First run the following command to connect application locally.

adb devices

Using adb command we can connect to the application locally. From there we can run npm start command to watch the changes in the background. To enable development server we simply run the following command.

npm start

Now we can build android app using the command below. This command helps to install the app on emulator and will listen to the code changes then update the application as we make changes. React Native comes with fast refreshing effect which is extremely useful as it preserve the state of the application while reflecting the changes we make to the apps realtime.

npm run android

In addition to emulator tool, we can also use so many open source tools since React Native is Javascript development environment. For example, we can use tools such as Typescript, Ignite UI CLI and Expo to build React Native apps more quickly and efficiently to give you more starting point to the project.

When it comes to flutter, we can achieve the same simplicity. For example we can launch emulator using Visual Studio Code itself. The same hot reload feature is also available in flutter project because dart programming language support just in time compilation. To run a flutter project simply run the given command below.

flutter run

Performance

React Native uses Javascript to connect native components via a bridge. Flutter avoids bridge to interact with native components resulting a better performance for app run time and also for the whole development process.

Flutter uses Skia Graphics Library that means the UI is redrawn each time when any view changes. In flutter, most of the work is handle by GPU (graphics processing unit) resulting smooth and fast UI rendering. This is why flutter delivers animation run time speed of 60fps (frames per second).

However redrawing the whole view instead of just those widgets that change, can affect the performance and speed of the application. Therefore developers need to be very careful when they design and structure the widgets for the application, specially for large apps where views often changes.

Conclusion

Both technology is perfect for cross-platform app development, specially you want release your app on both android and iOS environment more quickly. If your team have is familiar with JavaScript, React Native is the framework for your choice.

If you want a powerful cross platform app with amazing look and feel and strong documentation backing it, Flutter should be your framework of choice.