Tag Archives: #programming

How to Add Tailwind CSS to Your Reactjs Project

Tailwind CSS to ReactJS project

Tailwind CSS is a utility-first CSS framework which is used to make your website more responsive and beautiful. It is well known modern CSS frameworks which helps to speed up the development and styling process significantly. If you’re new to Tailwind CSS please follow the official documentation of Tailwind CSS and find a good starting point at the project’s homepage at TailwindCSS.

Setting up your React project with Tailwind CSS is so simple and comprises only very few steps. In this tutorial you will learn step-by-step approach of installing Tailwind CSS into your React project and get started using Tailwind’s CSS classes for styling.

Step 1: Creating Your React Project

Creating your new React.js project is the very first step. The easiest way to create a new project is to use the create-react-app script on the command line.

npx create-react-app react-app-with-tailwind

Now, cd into the working directory.

cd react-app-with-tailwind

If everything goes well, you should be able to see your react project on the web browser when you run the following command.  

npm run start

Step 2: Install Tailwind CSS

Now install tailwindcss and 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

Tailwind will create two files. You need to make small changes so it will works well for our Reactjs project.

  • tailwind.config.js
  • postcss.config.js

Step 4: Configuring Template Files

You need to specify the path to our Reactjs project files by adding the following configuration setting inside tailwind.config.js. Make sure to add the paths to all of your template files in your tailwind.config.js file.

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

Step 5: Add the Tailwind directives to your CSS

Now add the @tailwinddirectives for each of Tailwind’s layers to your ./src/index.css file.

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

That’s all. You’re good to go! Let’s make use of Tailwind’s CSS classes within our main React component in App.js.

Step 6: Use Tailwind CSS In Your React App

Add the following code to App.js. Start the development web server by using the following command. Now you should be able to see the following result in the browser.

<div className="container mx-auto bg-gray-200 rounded-xl shadow border p-8 m-10">
      <p className="text-3xl text-gray-700 font-bold mb-5">
        Welcome!
      </p>
      <p className="text-gray-500 text-lg">
        React and Tailwind CSS in action
      </p>
    </div>
npm run start

You can find code for this tutorial in this GitHub repo

Best Free VS Code Themes 2022🤩

Best Free VS Code Themes 2022

It is already halfway through 2022 and if you are still looking for any VSCode themes, then here is the list of some of the most popular VS Code themes for 2022 so far.

List of the top 5 VSCode themes – My choice:

  1. Atom One Dark Theme
  2. GitHub Theme
  3. Night Owl Theme
  4. JellyFish Theme
  5. Sublime Material Theme

Atom One Dark Theme

One of the best dark theme port in the marketplace. Atom’s iconic One Dark theme for Visual Studio Code is so popular among developers who loves dark mode.

It has visually pleasing styles and well-blended color schemes, therefore it is considered as one of the most used themes, nearly 3.3 million download in the market place as of today.

Here are some of the stats:

  • No. of Installs:  3,279,542 installs
  • Rating:  4.81/5 (102)
  • Current version: v2.2.3 | 1/4/2021| Free

GitHub Theme

It is popular theme for developers who prefer GitHub’s classic themes. It comes with various new styles, simply you need to select any available theme during installation process. You can choose one of these themes.

  • GitHub Light Default
  • GitHub Light High Contrast ✨ new ✨
  • GitHub Light Colorblind ✨ new ✨
  • GitHub Dark Default
  • GitHub Dark High Contrast
  • GitHub Dark Colorblind ✨ new ✨
  • GitHub Dark Dimmed

There are also two older themes. Note: They might not get updated frequently and are kept for legacy reasons:

  • GitHub Light (legacy)
  • GitHub Dark (legacy)

Here are some of the stats:

  • No. of Installs:  4,349,035 installs
  • Rating: – (120)
  • Current version: v6.0.0 | 2/11/2022 | Free

Night Owl Theme

This theme is fine-tuned for those of us who really like to code late at night. It comes with both dark (Night Owl) and light theme (Light Owl). The color choices, background, and styling are perfectly suitable for developers who are having difficulties in low-light circumstances. ✨

Night Owl

Light Owl

Here are some of the stats:

  • No. of Installs:  1,463,301 installs
  • Rating: – (119)
  • Current version: v2.0.1 | 7/4/2021 | Free

JellyFish Theme

It is also a beautiful theme. The font (Hermit) and colors used by the theme is easy on the eyes. The colors used by this theme for highlighting code are Aqua Blue, Purple, Dark Yellow, and Pinkish-Red.

Here are some of the stats:

  • No. of Installs: 75,788 installs
  • Rating: – (5)
  • Current version: v0.0.4 | 2/8/2022 | Free

Sublime Material Theme

This is simply a port to align the style of the theme with the default VSCode chrome that cannot be changed atm. It has both dark and light theme options, however it was last update long time ago, in 2016.

Dark Theme

Light Theme

Here are some of the stats:

  • No. of Installs: 568,813 installs
  • Rating: – (25)
  • Current version: v1.0.1 | 11/27/2016 | Free

There are lots of amazing themes in the marketplace and these are just few. Must have themes at least in my opinion. Maybe you have a better choice and if you have any let us know your favorite theme that make you more productive.

If you want to know about best VSCode extensions for 2022 then please read this article.

Top 11 Best VS Code Extensions you Need in 2022!

The Best Machine Learning Books That All Data Scientists Must Read

best ml books

Machine learning is an exciting field that has been growing rapidly in recent years and it’s only expected to continue to grow as we move forward into the future. There are many different options and topics that data scientists can explore while they’re studying machine learning, but there are some core principles and key texts that you should definitely be familiar with if you want to be taken seriously in this industry.

Today, I’ll take a look at the top machine learning textbooks that I’m currently reading and why you should read as well.

1. Artificial Intelligence: A Modern Approach

Artificial Intelligence is a massive and multi-disciplinary field, so it’s no surprise that there are plenty of resources for those looking to jump into this field. The most highly rated textbook for AI students on Amazon is Peter Norvig and Stuart Russell’s Artificial Intelligence: A Modern Approach. This book was introduced in 1995, and has been updated multiple times since then. This is a heavy book with 27 chapters that covers problem solving and search, logic and inference, planning, probabilistic reasoning and decision making, learning, communication, perception and robotics. Basically everything from common algorithms to neural networks and natural language processing.

Topics Covered:

  • Logical Agents
  • Learning, communication, perception and robotics
  • Supervised, Unsupervised learning and Reinforcement Learning, Machine Learning models and Algorithms
  • Probabilistic Reasoning
  • Natural Language Processing

This book is not only for students but also used by many experts in the field. Here are a few reviews from academics and professionals in the subject.

Experts Opinions

I like this book very much. When in doubt I look there, and usually find what I am looking for, or I find references on where to go to study the problem more in depth. I like that it tries to show how various topics are interrelated, and to give general architectures for general problems … It is a jump in quality with respect to the AI books that were previously available. — Prof. Giorgio Ingargiola (Temple).

Really excellent on the whole and it makes teaching AI a lot easier. — Prof. Ram Nevatia (USC).

It is an impressive book, which begins just the way I want to teach, with a discussion of agents, and ties all the topics together in a beautiful way. — Prof. George Bekey (USC).

2. Deep Learning (Adaptive Computation and Machine Learning series)

Ian Goodfellow, Yoshoua Bengio, and Aaron Courville are three researchers who stand at the forefront of Deep Learning. It comes with general context and comprehensive knowledge on mathematical foundation of Deep Learning. This book is highly recommended to read if you want to start your journey with deep learning.

Topics Covered:

First few chapters cover mathematical concepts for deep learning. You will be able to grasp these without difficulty if you have a concise knowledge of linear algebra, probability and statistics. Part 3 covers Deep Learning Research which include different techniques and methods for deep learning which is quite challenging.

  • Numerical Computation
  • Deep Feedforward Networks
  • Optimization for Training Deep Models
  • Deep Learning Research

Experts Opinions

“Written by three experts in the field, Deep Learning is the only comprehensive book on the subject.” —Elon Musk, cochair of OpenAI; cofounder and CEO of Tesla and SpaceX.

“If you want to know here deep learning came from, what it is good for, and where it is going, read this book.” —Geoffrey Hinton FRS, Professor, University of Toronto, Research Scientist at Google.

3. Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems 2nd Edition

This book is is a must-read book for everyone who seriously wants to enter this field. This is the perfect book for machine learning practitioners as it covers the most important aspects of machine learning, such as classification, regression, clustering, and dimensionality reduction. It simplifies highly complex concepts through concrete examples and real world example. It also provides detailed introduction of popular frameworks such as Scikit-Learn, Keras and TensorFlow. Author Aurélien Géron has put all the concepts in a beautiful manner so you can gain an intuitive understanding of the concepts and tools for building intelligent systems.

You need programming experience to get started, so learning Python programming language would greatly help to complete this book.

Topics Covered:

  • Introduction to machine learning and history
  • Use Scikit-Learn to track an example machine-learning project end-to-end
  • Explore several training models such as Support Vector Machines, Decision Trees, Random Forests, and Ensemble methods
  • Use the Tensor Flow library to build and train neural nets
  • Dive into neural net architectures, including convolutional nets, recurrent nets, and deep reinforcement learning
  • Techniques for training and scaling deep neural nets.

Experts Opinions

“An exceptional resource to study Machine Learning. You will find clear-minded, intuitive explanations, and a wealth of practical tips.” —François Chollet, Author of Keras, author of Deep Learning with Python.

“This book is a great introduction to the theory and practice of solving problems with neural networks; I recommend it to anyone interested in learning about practical ML.” — Peter Warden, Mobile Lead for TensorFlow.

4. Python Machine Learning – Second Edition: Machine Learning and Deep Learning with Python, scikit-learn, and TensorFlow 2nd Edition

You never want to miss this book If you really want to learn Machine learning. This is perfect book as its primary focus is exclusively on the implementation of a various machine learning algorithms. The book places a special emphasis on using Scikit-learn to implement these algorithms, and is a must for anyone looking to develop mastery around algorithm development.

Sebastian Raschka and Vahid Mirjalili has updated it to third edition in 2020, covering TensorFlow 2, ScikitlearnReinforcement learning, and GANs in the recent release.

Topics Covered:

  • Explore and understand the key frameworks for data science, machine learning and deep learning
  • Master deep neural network implementation using the TensorFlow library
  • Embed machine learning model in web application

These books are well worth to read if you want advance your machine learning knowledge and skills. I’ve printed copies of each book I mentioned above. In addition to that I also started to read several other ML books, pdf copies, watch YouTube videos and research papers to improve my ML skills and knowledge.

What’s new in Next.js 12: October 2021

Nextjs 12

Nextjs team has announced its latest addition, Next.js 12, the biggest release ever. Lets look into the improvements and new features that Next.js 12 offers to create and improve your web applications.

Speed test in Nextjs newest version

Faster builds and Fast Refresh with Rust compiler

Optimized bundling and compiling with ~3x faster refresh locally and ~5x faster builds

To improve performance, Next.js replaced the Babel compiler with an extensible Rust compiler — SWC — that takes advantage of native compilation.


Read more

Introducing Middleware

You can modify the response by rewriting, redirecting, adding headers, or even streaming HTML.

You can run code before a request is completed, and based on the request, we can modify the response by rewriting, redirecting, adding headers, etc.

nextjs middleware

NextJs and ReactJS

Preparing for React 18

Zero client-side JavaScript needed

Features including server-side Suspense and SSR streaming support also React Server Components which allow us to render everything, including the components themselves, on the server

URL Imports

You can CDN projects like Skypack and esm.sh in your Next.js app.

You can import directly tooling from the CDN without any extra builds or installs.

skypack

Why You Should Use DigitalOcean for Your Next Project

why you should use do for your next project

DigitalOcean offers easy-to-use managed cloud hosting service with simple user interface and powerful command line tools, which make it easy to deploy your code quickly and manage your server from anywhere on the globe.

DigitalOcean has invested significant of money to its infrastructure to make it truly a complete cloud engine. They have expanded geographic footprint, and introduced new products such as DigitalOcean Kubernetes, App Platform, and Managed Databases to its infrastructure. Companies such as Gitlab, Slack, Ghost, Cloudways and Whatfix are using DigitalOcean for years now.

App Platform

DigitalOcean App Platform is very easy to use and you can get started with it right away. It also have a lot of great features so you can build, deploy, and scale apps quickly as possible. DigitalOcean will handle the infrastructure, app runtimes and its dependencies, that means you can focus more on your code and its business logic.

With DigitalOcean, you can scale your apps to handle traffic as it grows. It is very cost effective and effectively optimize resources as you scale your apps.

Kubernetes & Load Balancers

With Kubernetes, you can easily scale up and deploy containerized apps in clusters. If you’re ready to start using containers but don’t want to worry about managing them, DigitalOcean is a great choice. Load balancers on DigitalOcean are simple to set up. It helps to manage distribute incoming traffic across a group of Droplets and increase your application’s availability with Load Balancers.

Introducing a new $4 Droplet

If you have an existing business or other online presence, then you’re likely familiar with the cost of hosting and managing multiple server instances. DigitalOcean is introducing a new Droplet priced at $4/month encouraging more developers across the globe to try its Droplets. This Droplet comes with 1 vCPU, 512MB memory, 500GB bandwidth, and a 10GB SSD, perfect for developers want to learn new skills and proof of concept for the next big app ideas. The price changes will be available starting July 1, 2022.

Backup

Backups are an important part of any hosting environment, but they’re often overlooked or not easy to implement. Droplet backups have always affordable and simple to enable. Backup Droplets disk images once per week, priced at 20% of the cost of the Droplet. If you destroy the Droplet, backups will also be removed and purged. However snapshots, on-demand full disk image of a Droplet work opposite. They will still be on your account until you delete it even after the Droplet is removed. Snapshots can be used to restore an existing Droplet or create a new Droplet from that point in time.

Developer Support

DigitalOcean offers free 24/7 technical support. There are three levels of support provided by the support team to meet your needs. You can send inquiries and contact the support team agent at any time and get help. They also have an active forum, a community where users can post questions and get answers from other developers. In addition, you can find number of comprehensive articles, tutorials and official docs related to any products and services they provide to the customers.

Read 8 Important Ways to secure DigitalOcean Droplets

In summary here are the few reasons I use DigitalOcean:

  • They provide virtual machine, Kubernetes, App platform, storage, database, and many more.
  • Easy to use, economical, scalable, and adaptable for web.
  • Affordable, reliable and quick deployment.
  • Server quality is great and server spec is perfect for various business.
  • Droplet backups are easy to enable and affordable.
  • Excellent tutorials and articles provided by the community and expert.

DigitalOcean grow with a global community. Whether you’re a developer looking to deploy your next project or an enterprise business company looking to build out a new product, DigitalOcean has a solution for you. So what are you waiting for? Try DigitalOcean today with a $100, 60-day credit to get started. That’s enough resources to run a website or app that you can build and start growing a successful business.

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 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.

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

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.